#templates-archived
1 messages · Page 63 of 1
thank you 🙂
@fading spade I converted your message into a file since it's above 15 lines :+1:
The helper variable input_boolean.status_garage_door_unknown is set in an automation if an inconsistent state of the two opening sensors "garage_zu" and "garage_auf" is detected.
Is there a way to check for the entity "type" ie I want to ignore all lighting groups as I only want to see the individual lights not the group controls
doesn't look like its an attribute
{
'min_color_temp_kelvin': 2000,
'max_color_temp_kelvin': 6535,
'min_mireds': 153,
'max_mireds': 500,
'supported_color_modes': [<ColorMode.BRIGHTNESS: 'brightness'>, <ColorMode.COLOR_TEMP: 'color_temp'>],
'icon': 'mdi:lightbulb-group',
'friendly_name': 'Living Room Lights',
'supported_features': <LightEntityFeature: 0>
}
Another solution would be to check if the name contains "Group" (I would change the light to reflect this). I can't see in the pinned link a contains
I am confused what args you can use with selectattr?
https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.selectattr
They aren't documented?
With selectattr() you are using tests
{{ states.light|rejectattr('name', 'contains', 'Group')|selectattr('state', 'equalto', 'on')|list|length }}
This seems to work
I would still like to know if I can test for the "type" as the helper ui calls it. That way its name agnostic and I just ignore all light groups
Are these light groups created in HA?
Yes, from the HA helper tab
- "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..."
Check the 5th pinned message
excelent, thanks. Can you give me a quick tldr on why rejectattr('attributes.entity_id', 'defined') rejects groups?
Happy new year everyone!
i'm trying to create a condition for an automation that checks if 2 different entity value's are the same. (automatic cat feeding, check the required amount of food portions against the physically dispensed ones)
my guess would be that that is going to require a Template sensor, i have never done this before and using google really doesnt make it any more clear for me
Happy new year to you, too. I think you can use a template condition and compare the state values of the two entities:
{{ states('<id entity 1>') | int == states('id entity 2' | int) }}
Light groups created in HA have an attribute which lists the members. That part rejects the lights with that attribute
doesnt seem to work
most likely i do something wrong tho
ValueError: Template error: int got invalid input 'unknown' when rendering template '{{ states('<counter.bobo_benodigde_portie>') | int == states('<sensor.voerautomaat_bobo_portions_per_day>' | int) }}' but no default was specified
{{ states('<counter.bobo_benodigde_portie>') | int == states('<sensor.voerautomaat_bobo_portions_per_day>' | int) }}
Don't think you want the <>
{{ states('counter.bobo_benodigde_portie') | int == states('sensor.voerautomaat_bobo_portions_per_day' | int) }}
TemplateSyntaxError: unexpected char "'" at 59
Sorry I left a > in
no you didnt?
I edited it
oh lol
ValueError: Template error: int got invalid input 'unknown' when rendering template '{{ states('counter.bobo_benodigde_portie') | int == states('sensor.voerautomaat_bobo_portions_per_day' | int) }}' but no default was specified still errors out
This worked for me
{{ states('sensor.air_purifier_dust_level') | int == (states('sensor.air_purifier_fine_dust_level') | int) }}
I just used some sensors I had on hand
hmm
replace them with yours
so i just realized it needs to be a bit more complex
i need the output to be true if the value of the second entity is higher or equal to the first entity
😅
Use >= instead of ==
What about making a group with all lights that are in an area or all lights that exist?
Ie I add a new light to the living room and the living room group just inherits it and the houshold light group also inherits it? or is this sort of templating not valid in groups?
You can't dynamically create light groups. You can dynamically create old school groups, but those won't be a light entity
Ok, I saw a forum post you can use all when calling the on and off service.
Can you target an area too?
Thanks!
this helped me to go from 4 pages of node red to half a page with even more functionality 🙂 (For the automatic cat food dispensing)
Yes, you can target an area
For some reason, this template I got from this channel shows me 2 lights on when only 1 is on:
{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.entity_id', 'defined') | map(attribute='entity_id') | list | count }}
This is still the correct way to filter out zigbee2mqtt groups, right?
No, Zigbee2MQTT groups don't have that entity_id attribute, so you won't be able to filter groups out like this
There is no way to determine if something is a Zigbee2MQTT group from the attributes of such a group
Ah okay, so I am supposed to make groups in a different way? Like is there a better option?
I think I found it, a group in the helpers menu. I'll try that.
Edit: that worked 🙂
That works, but you'll lose a lot of benefits Zigbee groups have
Dang it, like what? Sorry I'm super new to HA. I just wanted to have a counter for the lights so that I can always quickly see if any lights are on.
Like sending a single command to turn a bunch of lights on at once. I put 'group' in the name of my zigbee groups to make them easier to identify and filter on
Can anyone help format a template so that the text stays on one line? I'm basically using this to send a notification to an led display but the android.text part sometimes overlaps onto a second line and then does not get display properly on the LED screen. So i am looking for whatever is extracted in the android.text part to kept on one line. Thjs is the current template - "text": "{{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.title') }} , {{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.text')
Example
{
"text": "Plymouth Argyle - Watford , 20' Goal: [1] - 1
Finn Azaz ",
"repeat": 2
}
The above is example of whats happening. The goalscorer is Finn Azaz and thats the part that doesnt get send to the led display properly as i take its becaise its on the next line instead of at the end of the line above it.
because a simple light entity does not include a list of entities, where as a group contains a list of entites
to answer my own question, this did the job - "text": "{{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.title') }}, {{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.text') | replace('\n', ' ') }} "
@exotic valve I did have this template working that checks if the name contains group. You just need to keep naming consistent
Th preview for my template shows unavailable . Does that mean I messed up?
Nvm. I had a bunch of mistakes
Hello! I am actually not sure if this is better suited in "templates" or "automation"; but let me start here.
Our dog has a GPS Collar (Tractive). It works quite nice.
But what I would like to do is to create a sensor of "how long was doggos latest walk?"
The problem is; I want to explicitly look at "Time between leaving "home" to returning to "home", REGARDLESS of any zones doggo passes in the interval (and this is what I can not figure out. The reason for this requireiemtn is that doggo will on 5 walks out of 7 pass at least one other zone.
I also want the solution to be "restart proof", so just starting a timer does not fly either.
How should I tackle this? I have a feeling I am missing something very obvious?
what do you want the sensor to display while the dog is on it's walk?
the duration of the last walk before that, or that he's currently outside?
I would be happy if it just showed the "duration of the walk" and was only updated when doggo returned home. But it would be nice to see "Doggo has been snifing about for X minutes".
You can create a trigger based template sensor which has two triggers:
- device tracker leaving home
- device tracker arriving home
When the device tracker leaves home, you update an attribute which stores the datetime when that trigger occurs. The state of the sensor will remain as it is (you can uste this.state for that)
When the device tracker arrives home again, you update the state of the template sensor, by calculating the difference between the time of that trigger, and the time stored in the attribute. That you can use to generate the sentence like you posted above
@marble jackal Hm.. Yeah, that tracks. And if i want a template sensor with triggers. That still is a configuration.yaml thing-only, right? Because the UI template helper is just for triggerless?
Yes, the GUI doesn't support trigger based template sensors (yet)
just need to filer the "arriving home" event to ignore changes from "unknown".. I guess?
does that happen?
I would use a state trigger. In that case you can use not_from: unknown
Just for a backstory. We have a nice elderly couple that walks him during most days. HOWEVER, I feel fairly certain that they are not (out of personal pride) not really honest on how long he's been out some days. And if we know he's just gotten a quickie during lunch we can try to plan for getting home as soon as possible after lunch.
As for the "unknown/unavailable", @marble jackal , I am once again thinging on what happens during restarts of HA.
well, you can use not_from for that
I have NO issue with doggo just getting a "five minute leg lift walk". But i'd like to know to be able to give hme a more proper evening walk 🙂
Now i look at the history of the tracker, which tells the story. But I'd just like to automate this to a push notice.. so to say.
template:
- trigger:
- platform: state
entity_id: device_tracker.doggo
from: home
not_to: [ 'unavailable', 'unknown']
id: walk_start
- platform: state
entity_id: device_tracker.doggo
to: home
not_from: [ 'unavailable', 'unknown']
id: walk_end
sensor:
# sensor config here
@marble jackal I think you have provided the "Least insane" way to do this. I thank you.
(and another possible reason for "unknown/unavailable" is of course "You forgot to charge the tracker, stoopid" 😉
If you need help with the sensor config, let me know 🙂
@queen viper I converted your message into a file since it's above 15 lines :+1:
@marble jackal I'll give it a go based on the EV-template-thing i found and didnt think before i pasted in the channel 😉
This looks like a good start
@marble jackal We'll see. I'm using the person entity and not the device tracker.. but that should be the same. Let's just wait for the real walk to happen as to not mess up my history with overriding in dev tools 🙂
Is there an "easy" way to support templates in custom cards or do we have to go the button-card way and implement our custom templating system as well?
Are you a card developer? In that case, it might be better to ask in #devs_frontend-archived
@marble jackal Oooh.. Doogo is off and the sensor is increasing. Let us hope that he passes into an adjacant zone. 🙂
Can you share the code, curious to see what you came up with
@marble jackal Certainly.. (where's my manners? 😉 ) This is what I have rigjht now.
https://pastebin.com/mzGZtT5F
you could let it output the full sentence instead of only the number of seconds
@marble jackal Yeah, fur sure. But, hey a quick test never hurt someone. Besides, I will probably end up formatting this sensor data differently in different notifications. So "raw value" should be fine for the sensor itself.
👍
it will never reach the else part of the if statement in the state value, it only updates when it's triggered, so there is no way it will get to that
never mind, you added a time patter trigger
you should recalculate it on the else part.
scrap all that, looks good!
@marble jackal Thanks. Again, i yanked that part pretty much verbatim from someone who had done a EV-charge time sensor. 🙂
small improvement
start: >
{% if trigger.id == "walk_start" %}
{{ now().timestamp() }}
{% elif trigger.id == "trigger_time_pattern" and this.attributes.start | is_number %}
{{ this.attributes.start }}
{% else %}
Idle
{% endif %}
@marble jackal What Am i not seeing as to different operation?
@marble jackal AAAh!
Human readable date attribute
You were returning Idle twice, once in an elif, once in the else
I removed the need for the elif
Funny. Really funny. I was just now thinking "Right, next to increase readability".
Oh.. You are right about that as well... Thank you.
is there a way to add in the new sensor template format a friendly name (Name without _)?
- name: wohnzimmer_comet_dect_current_temperature
unique_id: "Wohnzimmer Comet DECT Current Temperature"
unit_of_measurement: "°C"
device_class: temperature
state: "{{ state_attr('climate.wohnzimmer_comet_dect', 'current_temperature' ) }}"```
name will be the friendly name, you can use spaces and capital letter there
that will be slugified to the entity_id
i have tried it, he makes _, maybe i delete it before?
so:
name: Wohnzimmer Comet Dect Current Temperature will result in sensor.wohnzimmer_comet_dect_current_temperature
and the freindly name also have the _?
no, if you do this, the friendly_name will not have _
#Comet DECT Current Temperature
- name: "Wohnzimmer Comet DECT Current Temperature"
unique_id: "Wohnzimmer Comet DECT Current Temperature"
unit_of_measurement: "°C"
device_class: temperature
state: "{{ state_attr('climate.wohnzimmer_comet_dect', 'current_temperature' ) }}"
ah unique no need _ too, thanks i will try
unique_id is only for storing it in the database, it has no effect on the name or entity_id
unless you don't provide a name
so it would be better too give the unique a name with underscore or what you personally prefer? (so i have not problems when i forget a name?)
@marble jackal the friendlyname is also with underscores, in a other psot i read from a attibutes
This is wrong? https://community.home-assistant.io/t/add-bring-back-friendly-name-to-template-sensors/305717/62?u=stephanschleichstr13
That post refers to the behavious that the entity_id is now created based on the name, they want to be able to set the entity_id and name separately. They are now linked to each other
it doesn't have anything to do with underscores in the friendly name
ah ok, what can be the problem than?
What is your current code?
- name: "Küche Comet DECT Current Temperature"
unique_id: "Küche Comet DECT Current Temperature"
unit_of_measurement: "°C"
device_class: temperature
state: "{{ state_attr('climate.kuche_comet_dect', 'current_temperature' ) }}```
okay, did you reload template entities after making this change?
i have delte the existing sensor and let it create with them new
one moment, now its correct
after 3-5 minutes
then you most probably have a sensor.kuche_comet_dect_current_temperature_2 now
or maybe not (based on your last comment)
so i change all names now, thank you thefes for help
{% from 'easy_time.jinja' import big_relative_time %}
{% set year = now().year +1 %}
{% set new_year = year~'-01-01 00:00:00' %}
{{big_relative_time(new_year,language='nl')}}``` stopped counting the days?
seem to remember it did work ok before... (only thing of importance was updating to 2024.1.0b04...)
time since new year does work: {% from 'easy_time.jinja' import big_time %} {{big_time(now().replace(month=1,day=1,hour=0,minute=0,second=0,microsecond=0), language='nl')}}
hmm, strange
I'm looking in the code, but all macros are using other macros, and before I figured this out, petro probably fixed it himself
at least relative time plus works 🙂
hmm, i tried these template and the friendly_name is again with underscore. something wrong? (HA reboot i do too)
unique_id: "Feiertag Beginn"
state: >
{{ as_timestamp(state_attr('sensor.ics_2', 'start'), default=0) | timestamp_custom('%d.%m.%Y') }}
can you show this entity looks in developer tools > states
post a screenshot using imgur or similar
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.
I don't know why it does that, that's not normal behavior
are you up to date?
I'll have to look at the code, they changed something
No, nothign changed, just a bug for dates in the future
Hi guys.. is there a way to convert decimal to hex without using format?
why don't you want to use format?
so I tried it on the template editor where it is working but it ain't working with the rest integration
can't help without any context.
so my phillips wiz bulb gives me rgb values in an array.. I convert it to hex and format it because I want to pass it to an api
{{ '%02x%02x%02x' | format(state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[0], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[1], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[2]) }}
this return a hex value.. now I want to use this.. call an api https://www.thecolorapi.com/id?hex=template_value
working with template editor
`sensor:
- platform: rest
name: Bulb Color
resource_template: https://www.thecolorapi.com/id?hex={{ '%02x%02x%02x' | format(state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[0], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[1], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[2]) }}value_template: "{{ state_attr('light.wiz_rgbw_tunable_c0dd69', 'effect') or value_json.name.value }}"
value_template: "{{ value_json.name.value }}"`
I add it as part of this and it throws me an error - %x format: an integer is required, not LoggingUndefined
I just started this templating so please bear with me if this is a dumb error
Really odd as it did work just fine before. Think I even posted a screenshot of that somewhere counting down …
You most likely need the #
have you verified it works with just the hex w/o the tempalte?
Top ‘over 1 week’ etc uses that same template
Hello @mighty ledge ,
I am sure you remember working your magic on my apexcharts-card filter template 🙂
I have run into a problem and cannot find the mistake.
Then something is most likely wrong with your yaml, or you arent' waiting long enough for the polled value to come through
For some reason the exclude part only uses the first exclude word and ignores the others.
{% for i in range(1, 6) %}
{% set post = '' if i == 1 else '_' ~ i %}
{% if states('input_text.apexcharts_entity_exclude' ~ post) %}
{% set excluded = states('input_text.apexcharts_entity_exclude') | replace(', ', '|') %}
{% set ns.list = ns.list
| selectattr('attributes.friendly_name', 'defined')
| rejectattr('attributes.friendly_name', 'search', excluded, ignorecase=True)
| reverse | list %}
{% endif %}
{% endfor %}
How do I wait long enough for the polled value to come in?
rest sensors poll every 30 seconds
rest entities
you can force a poll by using homeassistant.update_entity
I have been looking over it and trying to find the problem, but it all seems logical to me. Can anybody see why this would only remove "input_text.apexcharts_entity_exclude" from ns.list but not e.g. "input_text.apexcharts_entity_exclude_2"?
Found it.
{% set excluded = states('input_text.apexcharts_entity_exclude') | replace(', ', '|') %} was missing the ~ post
Thanks for listening 🙂
Anyone have a template that outputs the last sunday of the month?
could it be the leap year causing an issue? just checked the 'old' template and that is still correct {%- set values = [phrase('week',60*60*24*7),phrase('day',60*60*24,7),phrase('hour',60*60,24), phrase('min',60),phrase('sec',1,60)]|select('!=','')|list %} {{values[:-1]|join(', ') ~ ' and ' ~ values[-1] if values|length > 1 else values|first}}
I doubt it, it's probably just some bug I overlooked
do you need an issue for it?
still, dont get why 1 week ago this worked just fine and now behaves like this
That's time, it's a pain in the ass
{% set some_datetime = now() %}
{% set last_day_of_month = today_at().replace(year=some_datetime.year, month=(some_datetime.month + 1) % 12, day=1) + timedelta(days=-1) %}
{% set last_sunday_of_month = last_day_of_month - timedelta(days=(last_day_of_month.weekday() + 1 ) % 7) %}
{{ last_sunday_of_month }}
Leaving this here to start ideas flowing, but as noted by @marble jackal this doesn’t work correctly.
Guys - I've got a whole bunch of device_trackers for fuel stations, with their longtitude and latitude. Perhaps Im thick, probably, but is there not an easy way to dynamically find the closest fuel station to a given entity? In this case, another device tracker, a phone. The idea is it will ping the phone the cloest fuel station when phone bluetooths to the car. The fuel stations have dynamic names i.e. asda_postcode so it would need to be asda*, esso* etc. (device_tracker.esso*).
I've messed around, battled with some chatGPT answers, but it seems way to difficult.
Your last_day_of_month will be the previous year in December, and in November it won't work (you will get month=0)
Crap you’re right
dates and times are the devil's handiwork
I’ll have to chew on that one some more when I get time. Happy if anyone else wants to take a crack.
{% set some_date = now().date() %}
{% set last_day_of_month = (some_date.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1) %}
{{ last_day_of_month - timedelta(days=last_day_of_month.isoweekday() % 7) }}
@lucid thicket this will work
4 days after the 28th to get to next month: brilliant. I wasn’t aware of isoweekday either. Always learning something in this channel. Nice job on this one.
Great! Thanks!
i m using this template {{ state_attr("switch.auto_meter", "current_consumption" ) }} but i need to have the , placed one number to the left how can i do this?
its now reporting 73,8kW but it needs to be 7,38kW
For example like this:
{{ state_attr("switch.auto_meter", "current_consumption" ) | float(0) / 10 }}
just letting you know the correct output came back today
yes, and my next alarm also had that. since no alarm was set it defaulted to beginning epoch, which is January first......
using .day..... {{(now()+timedelta(days=1)).day == (states('sensor.next_alarm_timestamp')|as_datetime()).day}}
flukes beause of {{(states('sensor.next_alarm_timestamp')|as_datetime())}} being 1970-01-01 00:00:00+00:00
fixing for now with {% set next = states('sensor.next_alarm_timestamp')|as_datetime() %} {{(now()+timedelta(days=1)).day == next.day and next.year != 1970}}
Any experts?
Maybe this could work? https://www.home-assistant.io/integrations/proximity/
The Petrol Stations are just map objects, not zones unfortunately. The list updates dynamically via the Fuel Prices add-in in HACS.
if they have lat/lon, just use the distance function
use distance macro distance('person.me', 'device_tracker.some_gas_station') will return the straight line distance in km
I have about 50 to choose from, and I want it to pick the "closest"
Sorry, HA is new to me, just in the midst of learning all the great features.
closest is always the closest to home, so if you want it closest to you, you'd need to use distance.
I would break up your problem into pieces. First step is to get a list of all your stations. Focus on that first. Once you can get those entity_id’s in a list, you can then figure out how to loop through that list calculating distance to each one. During the loop you can save the distance and entity_id associated with the closest one.
Don’t try to ask for the whole solution in one bite.
Thanks - that is helpful. Let me start working on the first part, getting a list of all stations.
petro, is there a way to have easy time display the worded date from a date time("2023-11-02 22:00:00") as "November 2nd 10PM"? or does it have to be built manually? like using custom time where you can say which parts of the date time to display.
This is a datetime representation that is very specific to the English language. Coding something similar that works for any language is a huge task so for these specific formats you can just do it yourself. Here's an example: {{now().strftime("%B %-d, %-I%p")}}
It's no exact match with what you want but it is as close as I can get it with just strftime. Here's some info on the formatting options. https://www.programiz.com/python-programming/datetime/strftime
ok so it would be: as_datetime("2023-11-02 22:00:00").strftime("%B %-d, %-I%p")
November 2, 10PM
Need some help conceptualizing a solution. I have a dozen temperature vakue entities and corresponding expected value entities. I want to generate an alert whenever the difference between any tuple > 2. I also want to ignore the difference if the expected value is > 100 (purposedly set high).
I have the jinja to test for those conditions and find the difference. Soinds like I need to iterate over the whole list and find any offending temps. And how to turn that into a list, then alert if the list isn't empty.
Does that sound like the right approach?
@thorny steeple this section will help with templates
thank you
Hi
I've some problems with a REST template sensor.
Root of the problem is a buggy API of my washing-machine. Nothing I can change easy. So I have to deal with that.
I want to read out the endtime. If I request over HTTP I can get:
- no answer
- json ".error"
- json "valid output" -> machine inactive = true
- json "valid output" -> machine inactive = false
Only the last state is relevant as for all others I do not have an endtime.
So I did a "availabiliy" statement in the REST sensoe like:
availability: "{{ value_json.Inactive == 'false' }}"
But I can still see errors in my log because it failed to render the sensor itself. Any ideas why this happens?
Are you able to get what integration an entity or device was created with?
There is no integration. I used a REST sensor which does the HTTP calls
hey, I need some help or guidance, I have GPS tracking on my car that i can access via a web service.
currently, i have inputs for lat and long, but it isnt a device tracker, so does not show on the map
Can someone please help me with a device tracker template where i can then use device_tracker.see to update?
if you have lat/lon on a sensor, it'll show up on a map if you attach it to a person.
otherwise you can make an automation using device_tracker.see service to create a device_tracker that mirrors your sensor.
this is what i want to try. currently, the data is in 2 separate sensors. want to use an automation to a single entity
the automation part is fine. going to use Node-Red for that
Well then you need to come up with a way to do that in node red
the service call is simple
Why does 100 evaluate to true for le
{{ ((states.sensor | selectattr('entity_id', 'search', "_battery$")))|selectattr('state', 'le', '20')|map(attribute='state')|list }}
{{ ((states.sensor | selectattr('entity_id', 'search', "_battery$")))|map(attribute='state')|list }}
['100', '100']
['100', '100', '86', '94']
it is simple, it just creates a device tracker
states are strings, not numbers
with a string 100 is less than 20 because 1 is less than 2 when evaluating characters left to right.
how do I evaluate them as floats then
or is it impossible 😦
map the value to a float
| map(attribute='state') | map('float')
then do | select('le', 20)
but keep in mind, you'll lose the link to your state object.
i.e. you won't be able to get the name from it.
TemplateRuntimeError: No test named 20.
you used selectattr when it should be select
you no longer need to use selectattr after you map the generator to the attribute state
thnx, I now understand. been trying to create a "device tracker" template .
Unfortunate I can't get the name anymore though. Was hoping that I could get a sensor with a list of bad batteries and a total count for icon templating
you can use namespace to keep the references but it makes it so you can't use a 1 liner
that would be fine by me, I am in the yaml anyway
Hi, i am having some trouble with my energy dashboard using helper entities for daily reset metering as those entities somehow do not inherit the correct device class from the parent
I think I've sometimes seen that too.... I just fix it with customize
customize?
where can I find help with Ian Richardsons 'Config Template Card Card'?
yes that made it work! thank you
Anyone have thoughts on this?
Sounds fine
Hey all, I know it is possible with a template to check if an automation was triggered in the last X hours but is it also possible to check when it last performed an action? So the last time the automation was triggered and all set conditions returned true.
I don't think it counts as triggered unless it gets through the conditions
Ok cool. Thanks!
Hi everyone! How would I turn these three sensors into attributes of a single sensor? https://hastebin.com/share/depulutula.yaml
You can do that with a template sensor. You can see an example here where attributes are being defined:
https://www.home-assistant.io/integrations/template/#state-based-binary-sensor---device-tracker-sensor-with-latitude-and-longitude-attributes
latitude and longitude would be the attributes
More info above in the docs: https://www.home-assistant.io/integrations/template/#both-sensor-and-binary_sensor-entities
Thank you, I will give it a try
I managed, thanks!
Okay, second question! I am trying to make an automatic list of cheapest hours of electricity.
{{ state_attr('sensor.nordpool_kwh_fi_eur_3_10_024', 'raw_today') }} returns the following list: https://hastebin.com/share/hugujejixe.css
How do I return the list sorted based on ascending 'value'?
Actually nvm, I think I got it
Use @marble jackal macro designed to do this
You can install it via HACS
Thanks! I went with {{ (state_attr('sensor.nordpool_kwh_fi_eur_3_10_024', 'raw_today')|sort(attribute='value')).0.start }} for now, but I'll check it out :D
Any dashboard templates?
you want #frontend-archived , templates are not what you think they are.
Guys is it possible to use a template in the entity filed?
I want to implement this gallery card, but i want too change the folder everyday.
entities:
- path: media-source://media_source/local/Cameras/Porteiro/2024/01/04
include_video: false```
Would be something like:
```media_source/local/Cameras/Porteiro/{{ now().year }}/{{ now().month }}/{{ now().day }}```
But i think its not possible, anyone knows another solution for this?
I have a space heater that has a rest api that allows me control. It seems like the fan template (https://www.home-assistant.io/integrations/fan.template/) is a good fit for functionality but it does not have a temperature control. Is there a way to incorporate the temperature into that template or would I need to make another entity like a template sensor on input to get this functionality?
Might need some more detail on the desired functionality, but have you looked at https://www.home-assistant.io/integrations/generic_thermostat/ combined w/ https://www.home-assistant.io/integrations/switch.template ?
Generic_thermostat looks very promising!
thank you for the pointer
@lone galleon I converted your message into a file since it's above 15 lines :+1:
@lone galleon the frontend doesn't support templating
You can make a script that has your templates and call that instead
Hi all. A Template Sensor I made that subtracts one sensor from another is getting the maths wrong!
template:
-
sensor:
-
name: "Total Electricity Used Today"
unit_of_measurement: "kWh"
state: >
{{ states('sensor.ems2234025_grid_import_power_today') | int - states('sensor.ems2234025_grid_export_power_today') | int | round(2)}}
Currently the two sesnors have a read of 43.8 and 0.1, but the template is giving 43.0 as the answer. What do I need to change?
you're only rounding the second sensor
if you want to round the whole result, put the equation in parenthesis
{{ states('sensor.ems2234025_grid_import_power_today') | int | round(2) - states('sensor.ems2234025_grid_export_power_today') | int | round(2)}}
That still gets the result wrong
... that's not what I said to do
I'm sorry. Can you edit the template so I can understand what you mean
I've tried a number of combinations of what you have suggested but it either gives me an error or the same result
I'm obviosly not getting the order right
state: >
{{ (states('sensor.ems2234025_grid_import_power_today') | float - states('sensor.ems2234025_grid_export_power_today') | float) | round(2)}}
That has worked, kind of. I now get the answer - 43.699999999999996
Also, I had to remove the ) from after the second float.
you should have copied and pasted his result exactly
You need that ) together with the ( I put in front of your template
the 2nd ) is needed, you clearly omitted the first (
Bingo! Sorry, I missed the first one. That's working now. Thanks both.
Hi guys, I am doing some cleanup of my HA installation and I have a few errors in my system log related to templates that I am unable to fix
e.g. this one here:
Template variable error: 'None' has no attribute 'split' when rendering '{% if state_attr('sensor.office_lights', 'friendly_name') is defined %} {% for word in state_attr('sensor.office_lights', 'friendly_name').split() %} {% if loop.index > 1 %} {{ word }} {% endif %} {%- endfor %} {% else %} {{ 'sensor.office_lights' }} {% endif %}'
Template variable error: 'None' has no attribute 'split' when rendering '{% if state_attr('binary_sensor.fensterkontakt_arbeitszimmer_rechts_state', 'friendly_name') is defined %} Fenster {% for word in state_attr('binary_sensor.fensterkontakt_arbeitszimmer_rechts_state', 'friendly_name').split() %} {% if loop.index > 1 %} {{ word }} {% endif %} {%- endfor %} {% endif %}'
Template variable error: 'None' has no attribute 'split' when rendering '{% if state_attr('binary_sensor.fensterkontakt_arbeitszimmer_links_state', 'friendly_name') is defined %} Fenster {% for word in state_attr('binary_sensor.fensterkontakt_arbeitszimmer_links_state', 'friendly_name').split() %} {% if loop.index > 1 %} {{ word }} {% endif %} {%- endfor %} {% endif %}'
Template variable error: 'value_json' is undefined when rendering '{{ value_json.state }}'```
I am unable to find where this is coming from, I don't understandy why it is happening, but I also don't understand where it is coming from. Is there any way to narrow it down?
search your configuration for those templates
the syntax isn't correct either. You're using is defined for something that will always be defined. You should change that to is not none, that should fix the issues.
That is the thing, I cannot find where it is supposed to be, and where I am using it intentionally it is "is not none"
What is the easiest way to do so? I already tried opening the raw view of the dashboard and searching in there. Did not find these templates
use any software that can bulk search in files, notepad++, vscode, etc
Just did a grep on the whole config folder for "is defined" and the only thing I can find is in the log
Any other place I could check?
it's not though, your templates literally have is defined in them in the errors, those is defined should be is not none instead
MQTT discovery
Could you please be a bit more specific? 🙂
xD
but if you have MQTT devices, and they were auto discovered, then the MQTT discovery can contain templates.
Ah ok I see, I have a bunch of auto discovered MQTT devices, where can I check for the templates?
The thing is, I have a templates in my dashboard that looks very similar to the onces with the erros
name: |
{% if state_attr('this.entity_id', 'friendly_name') is not none %}
{% for word in state_attr('this.entity_id', 'friendly_name').split() %}
{% if loop.index > 1 %}
{{ word }}
{% endif %}
{%- endfor %}
{% else %}
{{ 'this.entity_id' }}
{% endif %}
e.g. this one, I was getting the error regarding none and the .split and I tried to fix it by checking for "is not none" before that
that whole template is just wrong
Ok?
'this.entity_id' should be this.entity_id
in all cases
and the is not none will stop the split from failing
Yeah that is what I though, funny thing is it worked before (without the outer most if)... is there somehwere a template cache or something I can / need to clean?
there's no way it worked with 'this.entity_id' wrapped in quotes
I mean the output was as I expected 😄
literally impossible for it to work that way
It stripped the first word fromt the friendly name...
Not sure what to tell you, this.entity_id is a variable and you're treating it like the literal string 'this.entity_id' which is not going to be an entity on your system
I am using it in the frontend in an filter card, if this makes any difference
If the filter card put in some bullshit to transform the 'this.entity_id' from a string into your actual entity_id, then it would work
I don't use that card so I wouldn't know
Yeah that might be the case I guess, in the error you also only see the replaced names
I dont get it, Just as a test I removed all tempaltes that make any use of ".split" and restarted my HA. Still I am getting the error
clear your cache and refresh the page
You mean the log page?
Or might this error also be caused by another client that is still running an older verison of the dashboard?
yes that's possible w/ frontend cards
I assumed it happend server-side, but could it also be triggered by a client?
uff, Ok, this might explain it, have quite a few clients running
will try to close them all and try again
Wow... that was it...
Dumb question: How can I search for a string in a message?
I'm trying to find the string SRSP - AF - dataRequestExt after 6000ms and SRSP - ZDO - mgmtPermitJoinReq after 6000ms in a MQTT automation, this is what I have so far (mainly for testing):
platform: mqtt
topic: zigbee2mqtt/bridge/logging
payload: "on"
value_template: '{{ "on" if value_json["level"] == "debug" else "off"}}'
'abc' in some_value or 'xyz' in some_value
I am left with one last template error: Template variable error: 'value_json' is undefined when rendering '{{ value_json.state }}'
I could imagine that this is more likely related to some mqtt device... question is where to search for that. The string "value_json.state" is not used in my frontend or any config.
What are the places to check for, for the templates related to the auto discovered MQTT entities?
that's from z2m, wait for an update
Ahh, this is a known issue?
yes, from the 2024.1
Ah ok, great 👍
it's comging from the devices set to legacy
Set to legacy where? in z2m?
Hi guys. Looking forward for help with a yaml template multi line sensor. The idea is to have a sensor that translates a Height into a text:
{% set height = states('sensor.desk_2995_height') | float(0) %}
{% if height < 0.9 %} Sitting
{% elif height < 1.15 %} Standing
{% elif height > 1.15 %} Walking Pad
{% endif %}
This works in developer platform, so logic is supposed to be ok, but not sure how to put into the configuration.yaml file. Right now is like this:
sensor:
- platform: template
sensors:
Standing_status:
friendly_Name:"Standing Status"
value_template:
{% set height = states('sensor.desk_2995_height') | float(0) %}
{% if height < 0.9 %} Sitting
{% elif height < 1.15 %} Standing
{% elif height > 1.15 %} Walking Pad
{% endif %}
but i got an indentation error. Pastebin of the yaml: https://pastebin.com/Z2fkA0dw
Isn't it supposed to be "states" not "sates"?
Ah nevermind, in your pastebin it looks ok 😄
yes, it is. I have deleted that letter while paste and editing here 🤣
Thank you @mighty ledge for your help!
Ah, are you refering to the legacy mode of the availability payload? This is actually enabled for some reason in my setup. I disabled it now and I check if this changes anything
Yeah that seems to be it! Thank you
Now I am almost error / warning free, but the rest is not related to templates and most of them need fixes by the developers xD
Using this to send notification of door open duration. It works, but often reports duration from an "opening" ago. That is to say, the door opens (A) and reports proper time. Door closes. Door opens again (B) and reports time from (A) using the following code. Any advice on a better duration template?
service: notify.mobile_app_dab
data:
message: >-
{{ trigger.from_state.attributes.friendly_name }} has been open for: {{
(now() - trigger.from_state.last_changed).total_seconds() | int // 60 }}
minutes.
what you're saying isn't possible
you're only using the trigger entity, which will be the triggering entity only, i.e. it will only report what triggers, it will never caculate based on a non-triggering entity
Is it possible to access the items of a todo list using jinja? I want to get the list and use it in a template sensor to randomly pick an item. But for that I somehow need to access the list.
template:
- trigger:
- platform: time_pattern
hours: '/1'
sensor:
- name: random_meal
state: >
{{ states('todo.meals') | random }}
statesis of correct false as the state is the number of items. But tried other approaches and all I could find were service calls.
Yes, this is covered in the docs
Only the state issue I already mentioned. Did not see anything on direct accessing using templating.
There is no direct access using tempaltes
you have to call a service to get the returned data, just like forcast
if you want it in a template sensor, then you need to use the new action: section for template sensors with a paired trigger.
Thank you, I will check that out. Just noticed that my next update isn't due until tomorrow, so I will test once updated to 2024.01 🙂
It’s not possible to pull the time of trigger and now time?
Thanks for the advice! 👏🏻
The time of the trigger will typically always be now. You can get the to_state and from_state times from the state objects attached to the triggers.
That makes sense. I’ll delve into it… thank you. 🙏🏼
Is there a way I can make this work for auto entities?
type: custom:mushroom-template-card
primary: |-
{% set entityname = (entity) %}
{{state_attr(entityname, 'friendly_name')}}
secondary: |-
{{ state.attributes.last_triggered.timestamp() | timestamp_custom('%H:%M') }} : {{ state.name }}
icon: null
icon_color: green
multiline_secondary: true
for the secondary line to show last triggered on an automation
that should just work assuming that your entity is set to an automation
Can somebody tell me how I can use the repeat for_each with the values I get from state_attr()?
(for example, I want to send a message for every attribute of a sensor. How could I do this?)
I now tested
automation:
- id: Meals
alias: Meals
trigger:
- platform: time_pattern
minutes: '/1'
action:
- service: todo.get_items
target:
entity_id: todo.meals
response_variable: mymeals
which apparently creates the variable according to traces
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
but dev tools report UndefinedError: 'mymeals' is undefined
{{ mymeals['todo.meals']['items'] | list | string }}
Variables aren't system-global
you have to build your template inside your automation where mymeals exists
Do you by any chance know if I can use a template to set the value of an input_text in an automation?
- service: input_text.set_value
data: {{ mymeals['todo.meals']['items'] | list | string | random }}
target:
entity_id: input_text.meals_1
Home Assistant seems unpleased with my approach
Error loading /config/configuration.yaml: while scanning for the next token
found character '|' that cannot start any token
in "/config/packages/frontend/meals_automation.yaml", line 13, column 45
My template was supposed to create a list and then randomly pick one of the items.
after defining the variable
- service: todo.get_items
target:
entity_id: todo.meals
response_variable: mymeals
Thought maybe I need to specify it as a template, but that was not it.
- service: input_text.set_value
data:
template: {{ mymeals['todo.meals']['items'] | list | string | random }}
Yes, but you need to follow the docs for setting the value of an input_text
Seems you're trying random things
I am using this in another automation
action:
- service: input_datetime.set_datetime
target:
entity_id: input_datetime.start_datetime
data:
timestamp: >
{{ (states['input_datetime.end_datetime'].attributes.timestamp-86400)|float }}
And merely adapted for the new one
Not really
You stuck a template right after data:, then made up the 'template' key
I am pretty sure I used the template key before, but seemingly not for this.
There's even an example of exactly what you want
And I missed the "
Many things
template: is only valid to introduce a block of template entities
Hello, I'm new with home assistant, and facing an issue creating a statistics sensor.
My configuration.yaml contains this;
sensor: !include_dir_list sensors/
in sensors/ i have (currently one) sensors file containing this;
- platform: statistics name: Eloverblik Monthly Statistics entity_id: sensor.eloverblik_energy_total sampling_size: 50 state_characteristic: mean max_age: days: 30
On load i get this error;
Invalid config for 'sensor' at sensors/eloverblik.yaml, line 1: expected a dictionary '', got [{'platform': 'statistics', 'entity_id': 'sensor.eloverblik_energy_total', 'name': 'Eloverblik Monthly Statistics', 'sampling_size': 50, 'state_characteristic': 'mean', 'max_age': {'days': 30}}], please check the docs
What am i missing ?
include_dir_list takes a bunch of files and concatenates their contents into a set of list items. My guess is that you need to remove the leading - and move everything 2 spaces to the left
Thanks @inner mesa that was excactly the issue - now the sensor loads as it should!
Is there a way to make variables temporarily global?
I find it a bit difficult to test my template without being able to modify it "live".
value: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | rejectattr('summary', 'search', states(input_text.meals_1)) | list | random }}"
I am simply trying to exlude any value that has already been written to the input_text.meals_1 so I don't create duplicates in the next service call
To start, you're missing quotes around the entity_id
darn it
The way to do what you're asking is to execute the service call in the dev tool and then assign the result to a variable in the template dev tool for use in your template
And no, you can't ever make a variable global in that way
Is home assistant's location (lat/lon) availabe in templtes in the latest release?
zone.home has always had lat/lon. Can that be assumed to be the same thing as "home assistant's location" ?
awesome 🙂
I see zone.home does follow homeassistant.set_location too. So that's probably good to use.
I wanted to check for the existence of a file before using it but my code always returns true.
Does anybody know if there is a detail wrong or if this is generally not possible?
{% if '/local/images/test.jpg' -%}
true
{% else -%}
false
{% endif -%}
Is there a simple way to build a template that creates a ternary (binary but 3) entity for security— green for all good and disarmed, yellow for potential problems, and red for armed? Right now, I’m just imagining a ton of and/or statements sandwiched between a few if/elses, and that seems wrong. There’s about a dozen entities (sensors and locks) in the mix to determine the security status.
Or is this better suited for a different solution?
Doesn't seem wrong to me... kind of depends on the specifics, but you're not going to get around 2 conditions and an else
You can use a template alarm. The services are optional, so you can use it as a read-only display of your alarm status
https://www.home-assistant.io/integrations/alarm_control_panel.template
If that doesn’t meet your needs, the other option is a template select which can hold any number states:
This looks promising. Even if it doesn't solve my problem, it still looks like something I would want. I'll check it out when I get back home.
Thank you!
And @obtuse zephyr , that was my thinking too. Hoping mekaneck's suggestion simplifies things a little.
anyone please help with why this label: "[[[ return variables.ulm_translation_state + ' - ' + relative_time(states['lock.kwikset'].last_changed)]]]"
keeps showing reference error. Im just trying to convert the last_changed UTC time to relative time
dashboard returns ButtonCardJSTemplateError: ReferenceError: relative_time is not defined in 'return variables.ulm_translation_state + ' - ' + relative_time(states['lock.kwikset'].last_changed)'
Create a sensor template then add states to that.
That's also one way
Do the whole thing in a template sensor and then just return the state in JS, or maybe JS has an equivalent to relative_time 🤷
One option could be using the file size integration and just monitor for whenever the sensor changes to >0
https://www.home-assistant.io/integrations/filesize/
Thank you for the suggestion. I did look at that earlier also but if I am not mistaken the file size sensor canker be created in the fly.
I will be checking for the existence of files based on user input and a Todo list with~100 entries. So I would need to create (and delete) lots of sensors automatically then.
Hi.
I`m looking for a way to count open doors & windows in rooms.
Is there a way to use a helper for counting windows in a room with open state, or do i need to create a template to solve this ?
You can do that using a template helper
MAybe a template wiz knows a smart approach that I could try to create myself.
I am trying to create 5 random entries for 5 input_text helpers. But I want to make sure that they are all unique, i.e. no input_text is the same.
Can anybody think of a way of doing that without manually rejecting each of the other input_texts?
My basic approach for two would be
- service: input_text.set_value
data:
value: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | list | random }}"
target:
entity_id: input_text.meals_1
- service: input_text.set_value
data:
value: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | reject('equalto', states('input_text.meals_1')) | list | random }}"
target:
entity_id: input_text.meals_2
mode: single
But I would like to create 5 and not repeat the reject(). But I am a bit stuck, creatively
When you check the state in the template, make sure the state is actually "open" and not "on". I had that in the past, where the state did not match what I see in the frontend.
Is there a way to reset all todo list items at once?
- service: todo.get_items
target:
entity_id: todo.meals
data:
status: needs_action
response_variable: mymeals
- service: todo.update_item
target:
entity_id: todo.meals
data:
item: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | list }}"
status: "completed"
My attempt failed and I am not sure if maybe there is a simpler solution that is not in the docs
hey template gurus, i have an entity that gives me the current grid consumption for my electricity. this goes negative when I am feeding into the grid and its positive when I am using grid energy. I am trying to set up automations thru a blueprint to use my excess solar for certain entites. this blueprint needs an entity for the export power and one for load. can I at least get the export power out of this entity via a template sensor? still trying to figure out the load one...
Can't you just check if your grid consumption entity goes negative? And then trigger the automation? Then you would not need to create new sensors.
Or maybe I misunderstood your approach, sorry
Do you by any chance have a example on this?
Hi, can somebody help me with my template? Following the instructions https://www.home-assistant.io/docs/configuration/templating/, I got most of the way there but I'm just having trouble with the time. Here's the working template: due_datetime: "{{ now() + timedelta(days = 15) }}" I need this same thing but always make the time 12:00PM. I'm trying to convert this template for use in the todo.list without making weird and wonky times. I tried sending just the due date but I get errors: Error running action Could not parse date for dictionary value @ data['due_date']. Got None I also tried just overwriting the time in a subjequent step but I saw no way to send time only without a date.
I would just change now() to today_at('12:00')
worked perfectly, thanks. I understand the sturcture better now. Thanks
I'm trying to get current week. It seems as jinja doens't have a week property as it eg year {{ now().year }} have. Any suggestion to week? {{ now().week }}
Like week number?
yea exactly
{{ now().isocalendar().week }}
awesome, thank you
now() returns a Python datetime: https://docs.python.org/3/library/datetime.html#datetime.datetime.isocalendar
So you can use any of the datatime functions on it
Do you mean on where to find out what the state really is or an example of how to check?
{% if states('sensor.blah') == 'on' -%}
true
{% else -%}
false
{% endif -%}'
Also possible to use elif instead or in addition to else
If you don't want to use true and false you can also perform something using {{ do something }}
A few good examples here: https://www.home-assistant.io/docs/configuration/templating/
how do i get the previous event from a calendar?
I want to take some JSON that comes in via a webhook (from woocomerce) and parse out some info to create todo items. I generally know how to do this, but I'm stuck on one thing, the json will contain a field called line_items, if there is just one item they will be under line_items[0], if two items, there will be line_items[0] and line_items[1] and so on depending on the number of items. Whats the best way to handle this field? (this is what it looks like in JSON Path Finder: https://imgur.com/a/7Q543uc )
The automation wants to know how much is negative or positive I think separately- it’s what the blueprint calls for
got it ```
{% for item in trigger_json.line_items %}
Item: {{ item.name }}
Quantity: {{ item.quantity }}
Case Color: {{ item.meta_data[0].value }}
Antenna Color: {{item.meta_data[1].value }}
{% endfor %}
This can be simplified to {{ is_state('sensor.blah', 'on') }}
You need to use the calendar.list_events service call. Use something like this to get the events which ended the last 2 days
service: calendar.list_events
target:
entity_id:
- calendar.your_calendar
data:
end_date_time: "{{ now() }}"
start_date_time: "{{ now() - timedelta(days=2) }}"
- sensor:
- name: Grid Consumption Reversed
unit_of_measurement: kW
unique_id: 89c413f0-4e46-4ff1-862b-cd8946d917b0
state: >
{% set value = - (states('sensor.grid_consumption') |float) %}
{{ value }}
I have this sensor which shows my electricity grid consumption reversed. This shows a positive number if I am generating solar and exporting to the grid, and a negative number if I am importing from the grid. Is it possible to create another sensor off this to show exactly what I am exporting (i.e. a sensor that only shows the existing sensor from 0 and above?)
{% set value = states('sensor.grid_consumption') |float %}
{{ value if value > 0 else 0 }}
Something like that should do that
Or {{ [0, value] | max }}, although the if version is easier to read.
Hello all, I have a curl request that sends a request to another computer in my network to create an image. I'd like to automate this in HA and base the prompt (there are two that have to be the same) based on the state of a sensor, namely weather forecast.
This should generate a different image based on the weather forecast once a day which I then plan to create a pictures card in ha to display it
How do I create it such that the prompt field is modified on each request?
an example prompt could be:
a house in the mountains on a {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} day, in the style of light maroon and sky-blue, poetcore, light gray and light brown, 32k uhd, light yellow and navy, consumer culture critique
I guess I can simply change the prompt to the above
in both fields
so the above definitly seems to work, if I inject that prompt with the state attribute, it comes out as
"positive_prompt": "a house in the mountains on a cloudy day, in the style of light maroon and sky-blue, poetcore, light gray and light brown, 32k uhd, light yellow and navy, consumer culture critique
",
- trigger: - platform: state entity_id: binary_sensor.alarm_sensorbb0003 to: "on" id: "on" - platform: state entity_id: binary_sensor.something001 to: "on" id: "off" binary_sensor: - name: my_sensor state: "{{ trigger.id }}"
if I have a tempalte sensor trigger based like this, but I want to turn it "on" only if a condition is matched (another sensor is true), can I add this condition only on the first platform: state and make sure that this condition is not considered if the second platform: state happens?
You can use a template trigger
Hello. I run into trouble as I don't find the error.... 😦 May you maybe help me out here?
- sensor:
- name: Heizung_COP
state: >
{% set q = states('sensor.mqtt_heizung_heizleistung') | float %}
{% set w = states('sensor.shelly_heizung_total_active_power') | float / 1000 %}
{% if w <= 0.5 or q <= 0 %}
0
{% else %}
{{ (q / w) | round(2) }}
{% endif %}
availability: >
{{
is_number(states('sensor.mqtt_heizung_heizleistung')) and
is_number(states('sensor.shelly_heizung_total_active_power'))
}}```
Hi, is there a way to calculate my monthly cost for something, I have a sensor of current wattage of a charger and then I have another sensor of my cost per kwh
Change the w variable to this to let the float filter work on the state string
{% set w = states('sensor.shelly_heizung_total_active_power') | float / 1000 %}
Else your are trying to divide a string by a number that will not work
you sir, are a hero. thank you very much.
You need to perform an integral on your kW sensor to calculate kWh, see the Riemann sum integration. Once you have that, you can use a template sensor to calculate kWh times $/kWh. You’ll also need to consider when to reset the sensor else it will just continue to increase (or maybe that is what you want)
Edit: take the Riemann sum sensor, then feed it into a utility_meter sensor that resets monthly
Next time, please say what's wrong. Few things are more frustrating than just saying that it doesn't work
I was not even able to see what is wrong. So, how could I?
I would normally just ignore such a request
oh you mean: "no output"
well, clearly something wasn't working
sorry, understood.
What isn't it doing, that it should be doing
I work in IT, I say that about 605054 times a day
I'm trying to have some logic for a dashboard variable. The counter prints the jinja text {{ 2 % 2 }} . I want it to return 0 (only an example).
- type: "custom:button-card"
template:
- custom_card_garbage_collection
variables:
label: test label
counter: >
{{ 2 % 2 }}
entity: input_boolean.garbage_collection_collected
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
other than using Spooks repairs entity, can we somehow find the repairs in HA states? asking because I need the repairs number and preferably with only core functionality
using this now {% set issues = states('sensor.active_issues')|int(default=0) %} {% set updates = states.update | selectattr('state','eq','on') | list | count %} {{issues + updates}} and use that for the notifications number on the configuration menu item
see https://github.com/home-assistant/frontend/blob/dev/src/components/ha-sidebar.ts#L551 is what the frontend does, Id like to do that in the backend....
so I can put a condition for one of the 2 triggers (I have 2) in the template trigger?
trigger based temlate (binary) sensors don't support conditions
so how can I do it?
you can do something like this:
- trigger:
- platform: state
entity_id: binary_sensor.alarm_sensorbb0003
to: "on"
id: "on"
- platform: state
entity_id: binary_sensor.something001
to: "on"
id: "off"
binary_sensor:
- name: my_sensor
state: "{{ trigger.id if is_state('binary_sensor.some_other_sensor', 'on') else false }}"
or
- trigger:
- platform: template
value_template: "{{ is_state('binary_sensor.alarm_sensorbb0003', 'on') and is_state('binary_sensor.some_other_sensor', 'on') }}"
id: "on"
- platform: state
entity_id: binary_sensor.something001
to: "on"
id: "off"
binary_sensor:
- name: my_sensor
state: "{{ trigger.id }}"
ah ok, clear, thanks
is there a way to get the state of a YAML configured input_boolean to be persistant after a HA reboot?
yes, remove the intitial line from your config, see https://www.home-assistant.io/integrations/input_boolean/#restore-state
BTW, this has nothing to do with templates, this is a topic for #integrations-archived
is there a reliable way to manually change a binary_sensor state? via API is still the right way?
What's the right way to mark a template sensor as unavailable? I'd like for a template sensor I've written to go unavailable when the sensor it depends on goes unavailable.
I've currently got {{ states('sensor.living_room_tv_power') | int > 10 }} but that errors in the logs when living_room_tv_power goes unavailable.
https://www.home-assistant.io/integrations/template/#availability ah I see there's this. Guess I need to set this up in YAML as opposed to the UI then.
Or specify a default value in the int filter -> | int(0) to always get a number as state
"{{ (states('sensor.solaredge_i1_ac_power'+'sensor.solaredge_i2_ac_power')|int(0) ) }}"
would this be the correct way to combine two sensors into one?
or can you put a , instead of the +?
No, the states function takes 1 entity id
"{{ states('sensor.solaredge_i1_ac_power') | int(0) + states('sensor.solaredge_i2_ac_power') | int(0) }}"
awesome thanks!
-template:
- sensor:
- name: Modbus Load
unit_of_measurement: W
friendly_name: "Load"
device_class: power
state_class: measurement
unique_id: fd32c3b4-8eec-4c41-a2ca-d96627e4257f
state: "{{ ((states('sensor.solaredge_i1_ac_power')|int(0) + states('sensor.solaredge_i2_ac_power')|int(0))
- states('sensor.solaredge_m1_ac_power')|int(0))}}"
Does this look right in its entirity?
just not sure how friendly name, device and state class are supposed to be formatted
the docs aren't very clear on this
they should be aligned with the other properties
template:
- sensor:
- name: Modbus Load
unit_of_measurement: W
friendly_name: "Load"
device_class: power
state_class: measurement
unique_id: fd32c3b4-8eec-4c41-a2ca-d96627e4257f
state: "{{ ((states('sensor.solaredge_i1_ac_power')|int(0) + states('sensor.solaredge_i2_ac_power')|int(0))
- states('sensor.solaredge_m1_ac_power')|int(0))}}"
ok, when I do that, the sensor does not work (disappears from HA)
What's your log say? Do you have the template integration configured more than once?
I have a template.yaml file, this has multiple instances of
- sensor:
- name:
...
- sensor:
- name:
...
if that makes sense...
sure... and this entry is just a single one in there then?
without the template: at the top
(If not, that's where it should go)
correct
fwiw i have other sensors with the correct formatting that you showed me and they work fine
Sure, that's why I mentioned checking the log... if you've got everything configured correctly, that will tell you what failed to set up
awesome, thanks, will take a look
hi all, im trying to parse the reply from a RESTful command, but RESTful command does not seem to support a value_template, do I have to create a second service to parse the responce?
https://www.home-assistant.io/integrations/rest_command/
thanks, Rob. But when would you want to use a RESTful Command vs Sensor? Does it have to do with refreshing it? for example, to refresh the command, I just need to call a service, but the sensor has its own interval....does that make sense?
If you want a sensor, use the sensor
If you just need a service, use the service
You can call a service whenever you want, like in an automation. Giving a service a refresh interval doesn't make sense
ok so this setup:
sensor:
- platform: rest
name: InvokeAI Last Image
resource: http://192.168.1.195:9090/api/v1/images/?is_intermediate=false&board_id=none&offset=0&limit=1
method: GET
unique_id: 13b8afba-1f27-4d0b-a1d8-0fc24a9d1f1d
headers:
accept: 'application/json, text/html'
content_type: 'application/json; charset=utf-8'
data_template:
json_attributes: true
value_template: "{{ value_json.items[0].image_url }}"
should parse out the url from the API output here:
{"limit":1,"offset":0,"total":11,"items":[{"image_name":"c16db7b3-6866-43c1-aa34-6a35dbb20736.png","image_url":"api/v1/images/i/c16db7b3-6866-43c1-aa34-6a35dbb20736.png/full","thumbnail_url":"api/v1/images/i/c16db7b3-6866-43c1-aa34-6a35dbb20736.png/thumbnail","image_origin":"internal","image_category":"general","width":384,"height":384,"created_at":"2024-01-08 06:00:02.276","updated_at":"2024-01-08 06:00:02.330","deleted_at":null,"is_intermediate":false,"session_id":"5f17cb52-25f9-45b0-b989-00fbe9e98bc2","node_id":"5bdc4138-e8f9-4682-bc3c-8fafcb3dd324","starred":false,"has_workflow":false,"board_id":null}]}
and how often does it update?
Heya! Whats wrong with this code? Trying to make a template switch with 2 services on both on and off. But it doesnt show up after restart:
https://dpaste.org/dTpD0
Thank you!
You didn't follow the format: https://www.home-assistant.io/integrations/switch.template/
Right, those examples goes right into configuration.yaml. But I use the code into templates.yaml so I suspected I did something wrong there 🙂 But shouldnt I just remove the " - platform: template" when I post it into the templates.yaml instead?
You can't just put it there
You have to do it the way the docs show
It's not optional
Ah ok! Will do like the docs, thanks!
can someone help me with the syntax example to add a mdi icon in a template? I want an icon in the secondary information.
type: custom:mushroom-template-card
primary: '{{ states(entity) | capitalize }}'
secondary: ''
@main nova I converted your message into a file since it's above 15 lines :+1:
You seem to be missing the preset_modes array at the very least
I don't think you can avoid having a "turn off", it's required by the template fan integration
Thanks, I could live with 'off' as the actual low mode, at least this keeps the UI clean with only 3 options and makes a bit of sense, given the 2 switches would be off.
ChatGPT has truly hallucinated most of that automation. Give me a second and I'll try tidying it up
It's been an interesting experience, It also kept adding 3rd switches and insisted on using old speed templates
So is switch.sonoff_100053c64c the medium and switch.sonoff_10004e540a the high?
Sorry missed that haha
No worries. So the preset_mode array would define what's visible in the UI?
https://gist.github.com/jackwilsdon/3c8b8538df72b3870c4eeb80c368a70f I've not tested it, but this should be closer. It always stays "on" and uses the preset mode to switch low/med/high
Yeah
I'm not 100% sure you can leave turn_on and turn_off empty like I did. If not, you could try putting an empty delay in them:
turn_on:
- delay: 0
Excellent, I'll give this a whirl.
Thanks a lot!
Hmm, not quite, I'm getting the following check errors:
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 170: 'condition' is an invalid option for 'fan.template', check: fans->ventilation_fan->set_preset_mode->0->choose->0->condition
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 170: required key 'conditions' not provided
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 171: 'value_template' is an invalid option for 'fan.template', check: fans->ventilation_fan->set_preset_mode->0->choose->0->value_template
My 170 is your 18
is it just a matter of adding the s to conditions? 😄
Sadly a bit more than that
I initially used if and switched to choice but the structure is abit diff
I've updated that gist: https://gist.github.com/jackwilsdon/3c8b8538df72b3870c4eeb80c368a70f/revisions
Also just noticed some odd quoting on the templates. The YAML formatter I used did that so not sure if it's right
great, thanks so much again, I'll try this in a bit
Unfortunately, even more screaming:
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 170: Unable to determine action 'fans->ventilation_fan->set_preset_mode->1', got {'conditions': [{'condition': 'template', 'value_template': "{{ preset_mode == 'high' }}", 'sequence': [{'service': 'switch.turn_on', 'target': {'entity_id': 'switch.sonoff_10004e540a'}}, {'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_100053c64c'}}]}]}
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 180: Unable to determine action 'fans->ventilation_fan->set_preset_mode->2', got {'conditions': [{'condition': 'template', 'value_template': "{{ preset_mode == 'medium' }}", 'sequence': [{'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_10004e540a'}}, {'service': 'switch.turn_on', 'target': {'entity_id': 'switch.sonoff_100053c64c'}}]}], 'default': [{'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_10004e540a'}}, {'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_100053c64c'}}]}
Unfortunately I don't understand enough about Jinja2 to even spot quoting issues
@rich anvil 👋
The template sections look ok in my file editor.
share what you're using
Me? The standard file editor in HA.
the code
Here is @rich anvil 's Github link: https://gist.github.com/jackwilsdon/3c8b8538df72b3870c4eeb80c368a70f/revisions
the important thing is what you're using
@main nova I converted your message into a file since it's above 15 lines :+1:
it checks just fine for me
my guess is that you put all that under template:
or in templates.yaml or something
no, it's in my configuration.yaml just under fan:. I have switch: right above and cover: underneath and both work fine.
I just pasted that whole thing as-is in my configuration.yaml and it checked fine and restarted without errors
that's interesting
I'm restarting in case something is lingering
nope, same issues after restart
your indentation is off
you need to indent everything in the choose: block
review the original again:
https://gist.github.com/jackwilsdon/3c8b8538df72b3870c4eeb80c368a70f
that's why it's important to see what you are using
I successfully copied and pasted it right out of the gist
Great, got it to check out, thank you! (Studio Code it is from now on)
@rich anvil it works! 🥳 Albeit with an on/off and separate presets, was hoping for a 3 level slider, but maybe this isn't an option in my case.
I am attempting to create a template binary sensor that is "on" if any entities that contain media_player.emby_ipad* or media_player.emby_iphone* are "playing" or "paused". I have gotten this to work which accurately counts any Emby players that are "playing". Not sure how to add "paused" or specify multiple entities.
{{ states | selectattr('entity_id', 'search', 'media_player.emby_*') | selectattr('state','eq','playing') | list | count }}
Use 'in', ['playing', 'paused']
is there something similar for the first selectattr so that I can specifiy media_player.emby_ipad* and media_player.emby_iphone* etc?
ok, I think I can make what I need work with the wildcard at the emby* level
thanks for the help
So the template I am using updates immediately in Template Editor. I created a binary sensor and the state does not change when I start to play media. It only changes if I go back to the template editor. Do I need to change something?
{{ states | selectattr('entity_id', 'search', 'media_player.emby*') | selectattr('state','in', ['playing', 'paused']) | list | count > 0 }}
states updates once per minute. Change it to states.media_player
I have a Template inside an automation question so I'm not sure which is best to post. I have a 4 button remote and want one automation to control all of them, instead of 4 individual automations. I'm capturing the trigger data but cannot get the template to read and compare. The evaluation comes back false. I've tried every combination I can think of and just can't get it working.
- condition: template
value_template: "{{ 'endpoint_id=2' in trigger }}"
then:
- type: turn_on
device_id: xxx
entity_id: xxx
domain: light
brightness_pct: 99
enabled: true```
The value of "trigger" is:
``` <Event zha_event[L]: device_ieee=xxx,
unique_id=xxx:0x0006,
device_id=xxx, endpoint_id=2, cluster_id=6,
command=on, args=[], params=>```
This explains how to extract information from an event trigger: https://www.home-assistant.io/docs/automation/templating/#event
"trigger" isn't enough
in your case, you would use value_template: "{{ trigger.event.data.endpoint_id == 2 }}"
here's someone doing something similar on the forum: https://community.home-assistant.io/t/creating-automation-around-zha-event-for-multi-button-switch/553292
Anybody know what is the equivalent of "data" is in the RESTFul Command? is it Payload?
I'm trying to use "data" in a RESTful command but its does not seem like an option (according to the docs): does the data need to be in the payload below?
rest_command:
get_LocalAI_image:
- name: "Parse Image URL"
resource: http://localhost:8080/v1/images/generations
method: POST
headers:
Content-Type: application/json
data:
prompt: "a prompt"
model: "dreamlike-photoreal"
size: "512x512"
value_template: "{{ value_json.data[0].url }}"
payload: "{{ value_json }}"
payload is what you need to send
you're treating it as though you're receiving it
and it seems like you're still using rest_command, when you should be using a rest sensor
This is where I get confused: I need to send and receive.
Send a request to generate an image
that's what that does
Receive to to tell me where it is
you send a command and get a response
So, rest command is correct?
Lol
OK I will do that again and post a revised yaml oh my lol
rob, this does not work the way I need it to. I don't need a sensor, I mean I do but not like this. Node Red?
https://community.home-assistant.io/t/how-do-you-get-the-response-from-a-restful-command/153055
Here's the scenrio:
- Send a curl request to an image generating AI machine once a day at 4 am which based on weather sensor (i.e. weather forcast) - so the prompt will be different all the time
- Wait upto 2 minutes for image to be generated and responce back
- Get image URL from the responce and place it it glaces picture card (or perhaps image entity)
it basically needs to be a service
called upon by an automation
ok
there's no way to get a response from a service like that
I still don't see why a REST sensor isn't what you want, but it's your thing
but is the sensor going to hit the machine on every update?
you can update however often you want
make the update interval once a day...could work
you control it
I'm sure they'll get rid of scan_interval one day and make this less hacky
ok, I could put this in:
scan_interval: 86400
what about restarts of HA?
it will likely force a refresh (i,e, and send a request) then
I don't know what happens on a restart
maybe sending a another command via command line to tell me what the last created file was in the images folder
ls -lat | head -2 | tail -1 | awk '{print $9}'
this gives me the file name
command_line:
- sensor:
name: LocalAI Last Image Created
command: "ssh name@192.168.1.195:8080/generated-images/ ls -lat | head -2 | tail -1 | awk '{print $9}'"
scan_interval: 3600
unique_id: e23e13a6-9354-4de5-8a7c-86fd3b2d0a9e
value_template: "{{ string | filename image entity?? }}"
Would this template sensor keep a list of everytime that this device goes offline?
- trigger:
- device_id: 3bc4bd9d1403a66c4fac7126026bfd55
domain: zha
platform: device
type: device_offline
subtype: device_offline
sensor:
- name: "zha Unavailable"
unique_id: zha_dead
state: >
{% set time_list = (states('sensor.zha_dead') | list) %}
{{ time_list.append(now()) }}
{{ time_list }}
and what triggers taht? I am trying to catch zha going into "initialising" in which every entity is "Unknown" or "Unavailable"
It doesn't work...
If you test the template in dev-tools you will see an important warning
I didn't put it in there because I expected the trigger to not be readable in it
There's no trigger mentioned in the template...
There are a couple of things wrong here.
| listdoesn't make a list out of a json string, you need to usefrom_jsonfor that.appenddoesn't work in jinja- the entity_id of your sensor will be
sensor.zha_unavailable(unless you change it). But you could also refer tothis.stateto avoid issues with the naming - this will soon exceed the 255 character limit for states
If you want to do something like this, put in in an attribute, not in the state. You can store lists in attributes.
.append doesn't work in jinja
I found multiple stack overflow for jinja .append. I thought templating was in jinja?
https://stackoverflow.com/questions/49619445/how-to-append-to-a-list-in-jinja2-for-ansible
the entity_id of your sensor will be sensor.zha_unavailable (unless you change it). But you could also refer to this.state to avoid issues with the naming
Didn't know they had object knowledge, cool
it's not supported in HA
If you want to do something like this, put in in an attribute, not in the state. You can store lists in attributes.
Can an entity just have any attributes? how do I "add" an attribute?
it's all in the documentation
and you can add items to a list, but not by using append
{% set some_list = [ 'a', 'b', 'c' ] %}
{% set new_list = some_list + [ 'd' ] %}
{{ new_list }}
[
"a",
"b",
"c",
"d"
]
and here is some information about the this variable https://www.home-assistant.io/integrations/template/#template-and-action-variables
Ok, so taking all of the suggestions, I have come up with this.
- sensor:
- unique_id: zha_errors
state: >
{{ this.attributes.failures | length }}
attributes:
failures: >
{% set old_list = this.attributes.failures | default('[]') %}
{% set new_list = old_list + [ now() ] %}
{{ new_list }}
state should be the length of the list, attribute will be the list of failures?
I didn't add the trigger
That's coming
You need the trigger for it to be persistent after a restart
- trigger:
- device_id: 3bc4bd9d1403a66c4fac7126026bfd55
domain: zha
platform: device
type: device_offline
subtype: device_offline
And after you add the trigger, this will be the state object at the time of the trigger. So with the templates like this, the state will be 1 lower than the the actual number of items in the list
I pulled this one from an automation, are they the same?
Yes, the triggers are exactly the same as for automations
Also, the first time it triggers, the attribute won't exist
- trigger:
- device_id: 3bc4bd9d1403a66c4fac7126026bfd55
domain: zha
platform: device
type: device_offline
subtype: device_offline
sensor:
- unique_id: zha_errors
state: >
{{ 1 + (this.attributes.failures | default([]) | length) }}
attributes:
failures: >
{% set old_list = this.attributes.failures | default([]) %}
{% set new_list = old_list + [ now().isoformat() ] %}
{{ new_list }}
You need a default there as well
edited
The default is at the wrong place
So if I default to []?
And if you want the state to match the number of items in the list, you need to add 1
The default needs to be before the length filter
Edited to match those two suggestions
And remove the quotes around [] for both default filters
You want it to be an empty list, not a string
This looks okay to me
cool, thanks for your help. I will slap it in and unplug the dongle to see what happens
ok, now it looks good?
👍
I unplugged the dongle and the sensor still just shows "unknown"
check the log if there are warnings/errors
and maybe create an automation with the same trigger, and see if that triggers when you unplug the dongle
to check if your trigger is correct
I have to adjust my wind speed sensor and multiply by 1.5. This works in the developer tools template but when I add it to my yaml, no sensor show up after restart of HA. What am I missing - sensor:
friendly_name: "Wind 1.5"
unit_of_measurement: "mph" # Adjust this based on the unit of your original entity
value_template: "{{ states('sensor.tempest_wind_speed') | float * 1.5 }}"
Thats from my config.yaml
what section did you put that in?
under template:
You're mixing legacy templates with modern templates
friendly_name and value_template are not usable in modern template yaml
name and state
Also, in-line comments will cause problems
with yaml
I used chatgpt to make it
well chatgpt isn't great for reasons like this
I see that now
now you see why it's use is banned (for helping others)
Might just want to make a Template Helper in the UI, a lot easier.
I tired that, I probablly didnt do it correctly
Got it
- sensor:
- name: "Wind 1.5"
unit_of_measurement: "mph" # Adjust this based on the unit of your original entity
state: "{{ states('sensor.tempest_wind_speed') | float * 1.5 }}"
Thx for the advice!
One more quickie, If I wanted the output value to be lets say 3.25 instead of 3.253, how can I add that to the line? Basically round to the 10th
Just add {{ (what you had inside other curly brackets) | round(2) }}
Thx
Hi.
I have custom:button-card to toggle my garage door.
The door gives open and close states, but is it possible to add "closing/opening" states from when i push the button and until its actually open by a sensor?
hello. how many "or" can I write into one "if" statement? like e.g.: {% if w <= 0.5 or q <= 0 or q > 10.0 %}
would that be possible?
as many as you want
hassio is stealing my life. i could invest so many hours into it. it's so much fun. - Thanks RobC!
no irony!
Suddenly my flic button is not working and apparently I have to make it only accessible from the local network, as per a warning in my HA settings page.
It tells me to click the gear icon beside the Webhook ID but there is no gear icon so I do not know what to do. I would attach images but there is no option. This might help https://community.home-assistant.io/t/update-webhook-trigger-issue/669961
@urban moat I converted your message into a file since it's above 15 lines :+1:
However I have the syntax wrong and I can't find in the docs how I should correct it.
The error given when I try to save that is Message malformed: expected dictionary @ data['action'][0]['default'][0]
you can't template service calls like that
you need to use script syntax to iterate over a list like that
actions:
repeat:
foreach:
{{ sensors }}
sequence:
- service: todoist.new_task
data:
content: Replace {{ repeat.item }} battery
Like that?
Apologies for my severly lacking YAML-fu
you need for_each: "{{ sensors }}", assuming that sensors is a list
I don't use blueprints, so there's some syntax around that that I'm not familiar with
Thanks! I'll take it over to blueprints and see if they can get me the last mile.
i have a shellyplug and i want to pull the status from it (the full status message) in a template sensor, how would i do that? 🙂
in a template trigger sensor the return of trigger.to_state.state is a string, right? so I can do something like: {% if trigger.to_state.state == 'stop' %} ?
All states are strings, so trigger.to_state.state will also be a string
@spark vortex I converted your message into a file since it's above 15 lines :+1:
it seems that the trigger to 'off' is not made for some reason, but it is made if I reaload the yaml
Is the binary sensor a template entity itself?
yes
- binary_sensor: - name: "Forno state" delay_off: minutes: 1 state: > {{ states('sensor.forno_power')|float(0) > 60.0 }}
but it happens also with other sensors that are not templte, but from an integration
it seems that the if statement is not triggered
@marble jackal any clue why this is happening?
I have a guess
the number input_number.forno_energy_per_cycle is updated by an automation, so I guess that the automation will be triggered after the sensor template trigger, so the value inside the input_number.forno_energy_per_cycle could be not updated yet at time of sensor template trigger
how can I make sure that the trigger template is updated always after the automation?
or I can probably update the sensor directly from the automation?
Why not then trigger on input_number.forno_energy_per_cycle changes?
because it changes 2 times: when the oven starts and when it ends, I just need the (end - start) value
service: input_number.set_value data: value: >- {{ ((states('sensor.forno_energy') | float) - (states('input_number.forno_energy_per_cycle') | float)) | round(4) }} target: entity_id: input_number.forno_energy_per_cycle
this is what I have in the automation when it stops
probably I should use a temporary input_number for it instead of using always input_number.forno_energy_per_cycle ?
Is is triggered after a YAML reload because your binary sensor will change from unknown to on
All template entities will go to unknown when you do that
yes, but it works because at time of restart, the input_number.forno_energy_per_cycle contains the right value
how can I update a sensor from an automation directly?
or make sure that an automation is ended before to update a template sensor
I could probably add some delay, but it could be not reliable always
for example, I want to run this
state: > {% set forno_state = trigger.to_state.state %} {% if forno_state == 'off' %} {{ (float(states('input_number.forno_energy_per_cycle')) * float(states('input_number.price_per_kwh'))) | round(2) }} {% else %} {{ -1 | float(0) }} {% endif %}
only if the automation X finished
uhm, if I add multiple triggers they will be in AND or OR?
triggers are always OR
can't make them in AND?
Combine them into one... only 1 trigger ever actually triggers something
uhm?
State your specific need and we can help out with the best way to structure it
ok, I will put on a pastebin to make it clear
these are my automations and sensors https://pastebin.com/MUbK9SY7 , the problem is that the template sensor will contain a wrong value, my guess is that because the tempalte tirgger is triggered before the automation STOP ends, so it will use the input_number.forno_energy_per_cycle updated in the START and not in the STOP automation
so a probably solution can be to add sort of delay in the template sensor after the trigger and before it set the state, is it possible?
Hi,
I have a question about a template.
The goal is that I get a value from the gas meter, where a certain value e.g. 700 is subtracted and that the value is then output in the unit of the gas meter. I have the following template:
- name: "gasconsumption"
state: >
{% set gasconsumption1 = states('sensor.gasconsumption') %}
{{ ( gasconsumption1 | float - 700 ) | round(2) }}
However, only the value is output here - without the unit.
If I use the following template, I get an error message because the calculation does not work, as the unit is included in the calculation.
{% set gasconsumption = states('sensor.gasconsumption', with_unit=True ) %}
{{ ( gasconsumption | float - 700 ) | round(2) }}
Can anyone help me?
@obtuse zephyr ok, found a better solution based on your suggestion (thanks):
- trigger: - platform: state entity_id: input_number.asciugatrice_energy_per_cycle not_to: - unavailable - unknown sensor: - name: Asciugatrice cycle cost unit_of_measurement: "€" state: > {% if states('sensor.asciugatrice_dryer_machine_state') == 'stop' %} {{ (float(states('input_number.asciugatrice_energy_per_cycle')) * float(states('input_number.price_per_kwh'))) | round(2) }} {% else %} {{ 0 | float(0) }} {% endif %}
Do you actually want to echo the unit measure in the state, as opposed to setting the attribute on the sensor as intended?
https://www.home-assistant.io/integrations/template/#unit_of_measurement
in https://community.home-assistant.io/t/heads-up-2023-6-longer-has-persistent-notifications-in-states-what-to-do/578654/155 i made a trigger based template to log repairs (almost identical to the one made for the persistent notifications) and it works ok, except on restart when it sets to unavailable. I believed to had guarded an empty list with a default, and yet the logger throws this
homeassistant.util.yaml.objects.NodeStrClass object' has no attribute 'data' when rendering ```
would appreciate a pair of eyes to help me out why this happens unlike the one for persistent notifications
Your history attribute is always looking at trigger.event.data, and it's indicating that that attribute doesn't exist on the event
Your repairs attribute is checking differently, as it's using an empty list of the trigger.id is start
If that's suitable for the history attr, you could mimic that
thanks for having a look. yes I figured that too, otoh, the failing history should take the else on HA start, so not use the trigger.event.data at all?
besides, the pers noti template does the exact same thing, unless my eyes deceive me now, why would that be different
wait, maybe I should add a check for trigger.event.data first? like {% if trigger.event.data and trigger.event.data.action == 'create' %} ?
no, it will first check the if and fail on that, as it doesn't have that trigger variable
or add an id to the update trigger? and check for that
on the Home Assitant start event you wont't have trigger.event.data.action
just do the same as for the repairs attribute
first check if it triggered on the start trigger
{% set rprs = this.attributes.get('repairs',[]) %}
{% if trigger.id == 'start' %}
not sure why you have that trigger though
oh wait, repairs probably have been fixed due to the restart
ok let me try that (had just clicked restart with the trigger.id for update, so next cycle... 😉
now see you both suggested the same thing...
yes this works too {% if trigger.id == 'update' and trigger.event.data.action == 'create' %}
that would work as well
which would basically be the same I guess, checking if it was actually updated. which btw isnt bad, as I noticed upon restarting just now, it is triggered twice
assuming you added that id to the trigger
first for restart, and few moments later, apparently for event
yes, I have this now:```
- trigger:
- platform: homeassistant
event: start
id: start - platform: event
event_type: repairs_issue_registry_updated
id: update```
- platform: homeassistant
so, given the fact the repairs_issue_registry_updated is happening on each restart, I could just aswell leave out that HA start trigger?
well, I don't know how it works for repairs like the restart required for a HACS update
I can imagine they are not cleared on startup, but just not created again
so if you don't clear the list on startup, they might stay in the list forever
yes, that was why I kept it in. Otoh, there are also persistent repairs on purpose, (see that service in dev tools) which I now clear in the state... I suppose that is not good. hmm
no, its needs to be cleared, because otherwise HA clears them (if theyre non persistent at least, and the sensor goes out if sync). too bad we can not see the Severity and Persistent in the data. and the Domain is just false.
{{ state_attr('media_player.media_group_all_google', 'entity_id') | select ('is_state','off') | list }}
i am currently using this to find all devices where the state is off. is there a way i can rewrite this to display the list of devices that have a State attribute called friendly_name that contains the word kitchen? so for example, return a list of all kitchen media players because they have kitchen in their name
{{ state_attr('media_player.media_group_all_google', 'entity_id') | expand | selectattr('state','eq','off') | selectattr('name', 'search', '[kK]itchen') | map(attribute='entity_id') | list }}
oh snap thats a lot more complicated than i thought it would be
okay i think i figured out a better way to do it, but i cant get the IF working. any thoughts?
@silent flicker I converted your message into a file since it's above 15 lines :+1:
line 7
value_template: "\"{{ repeat.item == 'media_player.aarons_room_display' }}\""
wait i think i just got it. a quote issue. NVM 🙂
too many quotes
yeah too many
value_template: "{{ repeat.item == 'media_player.aarons_room_display' }}"
that fixed it once i saw them in the raw editor
the loop is pointless though
unless you're going to add an else to that if statement
it was just a small snip
im changing the volume on all my media devices if they are OFF and im adding extra IFs to set different ones to different volumes
a daily "reset" of the volume in case people change them to make them too quiet to hear anything
Suddenly my flic button is not working and apparently I have to make it only accessible from the local network, as per a warning in my HA settings page.
It tells me to click the gear icon beside the Webhook ID but there is no gear icon so I do not know what to do. I would attach images but there is no option. This might help https://community.home-assistant.io/t/update-webhook-trigger-issue/669961
Trying to create a small batch addition script for To-Do Lists but my code only work in dev tools. In my script the counting does not work.
meals_batch_addition:
alias: Meals Batch Addition
sequence:
- repeat:
count: "{% set items = ["1","2","3"] %}{% set item_count = items | length %}"
sequence:
- service: todo.add_item
data:
item: "{{['items'][repeat.index-1]}}"
target:
entity_id: todo.meals
mode: single
Error: invalid literal for int() with base 10: '""'
You are not outputting anything for the count
Oh, I just see that I am setting the item_count and not returning it. I need to add {{ item_count }}
Op, nope, not quite.
count: "{% set items = ["1","2","3"] %}{% set item_count = items | length %}{{ item_count }}"
Leads to
expected <block end>, but found '<scalar>'
Apologies, I used double quotes inside the array and for the template 🤦♂️
Still stuck 😦
Error: length of value must be at least 1 for dictionary value @ data['item']
meals_batch_addition:
alias: Meals Batch Addition
sequence:
- repeat:
count: "{% set items = [1, 2, 3] %}{% set item_count = items | length %}{{item_count}}"
sequence:
- service: todo.add_item
data:
item: "{% set items = [1, 2, 3] %}{{['items'][repeat.index-1]}}"
target:
entity_id: todo.meals
mode: single
Tried with and without single quotes inside the arrays
the whole mess in todo items is... a mess
"{% set items = [1, 2, 3] %}{{items[repeat.index-1]}}"
Okay, found one issue: it must be `{{ items[repeat]}
assuming you're doing that oddness
Why oddness?
I tried not re-setting items but it seems it does not get the items from the count.
cause you made a 1 item list ['items'] and tried to get indexes beyond it's size
Also, you can probably do this w/ for_each and alot less jinja.
e.g.
- repeat:
for_each: "{{ [1,2,3] }}"
sequence:
- service: todo.add_item
data:
item: "{{ repeat.item }}"
target:
entity_id: todo.meals
hi! can you use scan_interval for a resful sensor setup?
sensor:
- platform: rest
name: "Image URL Sensor"
resource: http://192.168.1.195:8080/v1/images/generations
method: POST
scan_interval: 43200
timeout: 180
headers:
Content-Type: application/json
payload: '{"prompt": "Ultra high resolution 3D, {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} day on midwestern hay field in late fall. vivid landscape colors, Shot with Nikon D780 with Nikon AF-S NIKKOR 24-70mm f/2.8G ED lens, resolution 45.7 megapixels, ISO sensitivity: 100, Shutter speed 1/250 second, 12k resolution, award winning photography, trending", "size": "512x512", "model": "dreamlike-photoreal" }'
value_template: "{{ value_json.data[0].url }}"
According to the dragon, it updates on every restart and then at scan interval
I never argue with the dragon
😁
Having said that setting up as a sensor is the only east way I could do this short of an integration. If it hits the API on every restart is not a big deal cuz I don't often restart
Gosh. Anyone running Shelly 1 PM Mini with MQTT? I'm using it to monitor my solar power production however with the new devices Shelly also seem to have switched to a single "RPC" topic called shellypmmini/events/rpc which sometimes include the JSON parameter containing the power, sometimes it's outputting completely different stuff on the same topic. Then I am getting Template variable error: 'dict object' has no attribute (......) errors. According to what I found online that could be solved using availability but I couldn't wrap my head around it yet
https://pastebin.com/wmQhvvWz these are the shelly mqtt responses and my sensor
does not seem to like the formatting for this sensor,
http://pastie.org/p/0lmsTrdyYUnEwzPCg2lMew
it seem to be complaining about bad indentatoin of the {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} part, but I don't think that the case?
You have a multi line value without using a multi line indicator. Mixing tabs & spaces in YAML is also asking for a bad time
if you made payload: -> payload: >, removed the leading and trailing ', and fixed the mixed whitespace, you should be good
I asked this over in #blueprints-archived and got redirected back here. Is it possible to set a variable with results from a service call or to be able to make a service call from within a template? Related to my previous question in #automations-archived (#automations-archived message), the blueprint/automation finds all entities that have low batteries and I create a todo task (via Todoist) for each sensor needing a replacement. I would like to check if a todo already exists (via the todo.get_items service call) to exclude those entities so as not to make duplicate todos for ones that already have a todo. For reference, my blueprint is at https://gist.github.com/tteggelit/ff200972645b0d1f203605df10e6eb2a
Also, the automation I've currently created on this blueprint looks like the following.
Thank you! That was it. Works now.
If the state of that sensor is a url to a local image, should I now make an image entity based on this entity so that I could view the image in a picture card?
I know I can use templates in a shell_command. Is there a way for that template to have the trigger information from an automation?
For example I want to echo {{ trigger.event.data.tag_id }} >> tags_scanned.log' when a rfid card is scanned.
Once you set up the shell command, it will be available as a service which you can pass variables to like you would a script:
shell_command:
echo_tag_to_log: 'echo {{ tag_id }} >> tags_scanned.log'
service: shell_command.echo_tag_to_log
data:
tag_id: "{{ trigger.event.data.tag_id }}"
I tried something similar and it was not working so I was wondering if there is a templating problem, I am trying it a little differently (than I originally did) now, I'll see if its working.
shell_command:
write_card: "/bin/bash -c 'echo Scanned {{ tag }} >> /config/cards.txt' "
automation:
- id: "writecard"
alias: Write Card to File
trigger:
platform: event
event_type: tag_scanned
condition: []
action:
- service: shell_command.write_card
data:
tag: >-
{{ trigger.event.data.tag_id }}
now its working.
ok, nevermind the image entity...I simply used the generic camera integration and placed this as the path of the camera {{ states('sensor.image_url_sensor') }} and it works and updates when there is a new image. THanks!
Can you include the "lock.open" action to a template lock? The Nuki Matter integration doesn't expose lock.open as a supported feature, so the usual lovelace cards don't show the option anymore so I'd like to fix that with a template lock.
there is no lock.open service call
there is lock.lock and lock.unlock
oh wait, there is lock.open
sorry
but I don't see it in the template lock documentation, only lock: and unlock:
yeah seems like it's not implemented in the template lock
it is within ESPHome though, so I'm just using an existing ESPHome device in my network to accomplish this
@graceful sphinx I converted your message into a file since it's above 15 lines :+1:
would be great to have this integrated within the lock template 🙂
the keys are lock: and unlock:. Not lock_action: and unlock_action:
you could try if open: works as well, and maybe just isn't documented
the code above is from ESPHome
it didn't
I'd like to use the Mushroom number card with the slider to change the volume of a media player.
There is no volume entity by default in HA.
I created below template:
- name: keuken volume
unique_id: keuken_volume
state: "{{state_attr('media_player.harman_kardon','volume_level')}}"```
Restarted HA but still no volume entity to use the Dashboard card.
doesn't this just create a sensor with volume_level as state?
It seems I should create another type of sensor. I can't select the sensor in the Mushroom number card
maybe create a number template instead of a sensor? With that you can also define min/max and set_value
I'll figure out how to do that
To much info on https://www.home-assistant.io/integrations/template/ have to search for an example
Hmm, seems not to be used often. Best thread I found was https://community.home-assistant.io/t/template-number-e-g-for-volume-control/99622/8 but it doesn't really help
- number:
- name: keuken volume
unique_id: keuken_volume
state: "{{state_attr('media_player.harman_kardon','volume_level') * 100 | int }}"
min: 0
max: 100
optimistic: false
step: 1
set_value:
service: media_player.volume_set
target:
entity_id: "media_player.harman_kardon"
data:
volume_level: "{{ value | float / 100) }}"
this could work 😄
It won't though, volume_level is float
the qoutes around the template are missing
I do get: The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: invalid key: "{"((states('number.keuken_volume') | int) / 100)": None}" in "/config/template.yaml", line 14, column 0
volume_level: "{{ states('number.keuken_volume') | int / 100 }}"
also
state: "{{state_attr('media_player.harman_kardon','volume_level') * 100 | int }}"
yes, but you already had qoutes there
yeah but it would've spat out a float between 0 and 1
volume_level will also spit out a string which doesn't work
no, that's already a float
btw, you can use:
set_value:
service: media_player.volume_set
target:
entity_id: "media_player.harman_kardon"
data:
volume_level: "{{ value | int / 100 }}"
hmm I think we need to turn it back to a float for media_player.volume_set
I've adjusted my code above
my number entity spat out a string so better be safe
volume_level: "{{ value | float / 100) }}"
Hi, this created a sensor number.keuken_volume. Can select this entity in the Mushroom number card but the slider doesn't work to change the volume....
No, when I play with the slider the volume changes to 0
so it does something at least
I could help troubleshoot with Teamviewer or something, just shoot me a DM if you want
Sent you my ID and password
hi, I try to create a template entity which if an entity has the state "dnd" or "online" then the state "1" and otherwise "0" gets. I have the following code. Since I want to create many such variables, I wanted to use variables, but I can not address these variables in the template so far, how do I do that? {% set user = states('sensor.user') %} {% if {{user}} == "dnd" or {{user}} == "online" %}1{% else %}0{% endif %}
is your media player off?
@maiden magnet I don't beleive you need {{user}} in Jinja code. I think you can just write {% if user == ...
it won't have a volume_level then
you are indeed nesting templates, which you should not do
use user like shingle suggests
I'm guessing there's not a way to make a service call in a template the way I'm trying to do.
Your question doesn't make sense
either it's a simple answer, or i'm not understandign what you're asking
simple answer: todo.get_items is a service call that responds with data and you just set the response_variable
Let me first see if I can figure out what a response_variable is and if that is my solution. If not, I'll more thoroughly explain what I'm trying to do (and how I'm currently trying to do it, which may be completely the wrong way).
oh :D i thought i tried this :D now it works, thank you
Hi guys, im trying to create a sensor with a attribute of a sensor but i got a error. what wrong on thaht : - sensors: iphone_alex_zone: friendly_name: Iphone Alex Zone value_template: '{{states.sensor.iphone_53_geocoded_location.attributes.zones}}'
Ok. a response_variable looks like my best bet. If I'm reading it right, this will need to be done in the resulting automation from the blueprint, not the blueprint itself?
it's done in the sequence section for scripts or the action section for automations and template entities
What error do you get?
the indentation is wrong, the last 2 lines need two more spaces
@merry furnace I converted your message into a file since it's above 15 lines :+1:
also you should use state_attr() instead of states[].attributes[]
You right ! i miss indentation ! i just try it but they dont get the value. Also i try this in devtools/templates : {{ state_attr("sensor.iphone_53_geocoded_location", "zones") }} and they return None. But if i go on States and look the attribute zones i have a value
I wanted to use different services if boolean true and others if not true. Then a final service in any case. See code below.
This doesn't work and I have the feeling that this is because it should first give back an enter after the sequence.
Is what I try to do possible in such a way?
For now I have solved it with simply using a group, but the question remains.
sequence: >
{% if states('input_boolean.vacuum_once_a__day') == 'on' %}
- service: vacuum.return_home
entity_id: vacuum.antracii
- service: vacuum.return_home
entity_id: vacuum.silvii
{% else %}
- service: vacuum.start
entity_id: vacuum.antracii
- service: vacuum.start
entity_id: vacuum.silvii
{% endif %}
- service: input_boolean.toggle
entity_id: input_boolean.vacuum_once_a_day```
but does {{states.sensor.iphone_53_geocoded_location.attributes.zones}} work in devetools > templates?
I got this : 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'zones'
not like this, you can't template the whole yaml
sequence:
- service: vacuum.{{ 'return_home' if is_state('input_boolean.vacuum_once_a__day', 'on') else 'start' }}
target:
entity_id:
- vacuum.antracii
- vacuum.silvii
- service: input_boolean.toggle
target:
entity_id: input_boolean.vacuum_once_a_day
That means that the attribute doesn’t exist or that the key name is wrong
there is no attriubute zones, that's why the other option retruns None
either the entity_id or the attribute is wrong
check in devtools > states
Look at the screen shot. I have the attributes on states : https://frazhome.zapto.org/local/screenshot.png
your attribute is Zones, not zones
Oh ! Capital sensitive !
use state_attr('sensor.iphone_53_geocoded_location', 'Zones')
Ah i tried that earlier, but probably made some error as it didn't want to accept two entities.
that's because you were not using target
True I tried target and later data, but probably made some other mistake there.
I'll try it again.
I see btw that I tried it different than you are proposing. Your's is cleaner!
Alright ! i got the right value ! Now when i modify on my sensor i got a lot of red line. i think they missing something - sensors: iphone_alex_zone: friendly_name: Iphone Alex Zone value_template: '{{state_attr('sensor.iphone_53_geocoded_location', 'Zones')}}'
If I recall correctly you were also struggling with the same entity within custom:button-card right in #frontend-archived ?
Than the syntax would be
return states['sensor.iphone_53_geocoded_location'].attributes.Zones
This could remove the need to make the template sensor at all, as I expect Zones to be a list, what does not work quite well in a string-state
where are you placing this?
II was placing on my configuration yaml but i think i will do like Bas said. It will be easier
okay
I guess you placed it under template:
but you were using the legacy format, which should be under sensor:
for the legacy format it should be:
sensor:
- platform: template
sensors:
iphone_alex_zone:
friendly_name: Iphone Alex Zone
value_template: '{{state_attr('sensor.iphone_53_geocoded_location', 'Zones')}}'
I made the mistake @TheFes, I had -entity_id: xyz under targget, instead of just listing the -xyz.
Thanks for your help again!
I'm going to make other scripts cleaner based on your suggestion as well.
I noticed the input boolean entity_id has two underscores between a and day