#templates-archived
1 messages · Page 77 of 1
A number is ment to be used for a slider
so it will have a value that the user can adjust
a sensor is to output a value that the user can't adjust
Right - so it's an I/O distinction..
Yeah OK this maps to sensor then, I'll change that.
You're thinking too software oriented
Anyways, make it a sensor and you'll be able to do what you want without templates at all
Thanks @mighty ledge ! Appreciate it 🙏
NP
Got it kind of
post your two entities that would be used in the template
Worked it out I needed to create 2 helpers, one that gave me the difference between the two sensors then I used
template:
- sensor:
- name: "Inverter efficiency loss"
unit_of_measurement: "°%"
state: >
{% set loss_power = states('sensor.loss') | float(0) %}
{% set grid_power = states('sensor.input') | float(1) %}
{{ ((loss_power /grid_power ) * 100) | round(1, default=0) }}
Yep that should work, but you might want to go availability route over defaults
I looked at that but the sensors should never be unavailable
sensors are always unavailable during restart
Restart? >.<
template:
- sensor:
- name: "Inverter efficiency loss"
unit_of_measurement: "°%"
availability: "{{ 'sensor.loss' | has_value and 'sensor.input' | has_value and states('sensor.input') > 0 }}"
state: >
{% set loss_power = states('sensor.loss') | float %}
{% set grid_power = states('sensor.input') | float %}
{{ ((loss_power /grid_power ) * 100) | round(1) }}
Yes, when you boot up the system or restart, all states are unavailable
I don't do that
Thanks that looks nicer than the availability I found
You've never updated HA? You've never reloaded an integration? You've never restarted after adding yaml?
Sadly I was being sarcastic I wish I never had to update but as far as yaml and intergration restarts I rarely mess anymore so I tend to only restart at the end of every month or so. It was too much like a full time job for the first year or so now I take a very laid back approach.
Sorry having an issue with the availability section in this it doesn't seem to like the > 0
I'm using ```
template:
- sensor:
-
name: "Inverter efficiency loss"
unit_of_measurement: "°%"
availability: "{{ 'sensor.loss' | has_value and 'sensor.input' | has_value and states('sensor.input') is_number }}"
state: >
{% set loss_power = states('sensor.loss') | float %}
{% set grid_power = states('sensor.input') | float %}{{ ((loss_power /grid_power ) * 100) | round(1) }}
-
Is there any difference?
Put a | float after the states function in the availablility template
there is a | missing before is_number
well he doesn't want is_number
he wants to check if the value is not equal to 0
because that would be a divide by zero error
ah
availability: "{{ 'sensor.loss' | has_value and states('sensor.input') | float(0) > 0 }}"
yah, that would work too
@floral steeple I converted your message into a file since it's above 15 lines :+1:
generated_content.text yo
get rid of the extra period too
Motion has been detected at your bird feeder. {{ generated_content.text }}
thanks!
Is this possible?
variables: in_nighttime: - condition: time after: '22:00:00' before: '07:00:00'
The built-in time condition handles midnight roll-over, so rather not do my own...
there's no template there
but you cannot put a YAML condition in a variable definition, either
I want to set a trigger_variable to true/false based on a time condition. Like above, right now I'm duplicating that a ton through a blueprint. How would you approach?
You should put the time condition in the condition section of the automation. It doesn't belong in the trigger
This is a blueprint with 7 triggers, so can't do a simple condition like that
trigger variables are extremely limited
and they aren't reevaluated after arming the trigger. They won't be useful for this
you need to create a suitable condition
That is good to know, I thought they were eval each time
no
they are one and done, pretty much added for MQTT and event triggers only
Did you try any of the suggested changes I said yesterday?
Yes, huge cutdown in lines. Thanks
I need to know if time is between 2 times and trying to use a variable for that, but now I know why it wasn't working
you can use today_at
Problem with today_at is it doesn't handle midnight
it does, but you aren't thinking of it correctly
if it crosses midnight, use an or
{{ today_at('10:00') <= now() or now() <= today_at('7:00') }}
after 10 or before 7
Ok...
sorry, needs to be 22 for the 10:00 one
Yeah, let me try that
either way, that gets you between 10pm and 7am
Think I had problems converting to time vs datetime. Let me check
you could also do not
e.g.
{{ not today_at('07:00') <= now() <= today_at('22:00') }}
What did I get wrong here:
{{ trigger.id == 'DayTime' and not ((today_at(schedule_start) <= now() or now() <= today_at(schedule_stop)) and night_led_brightness == '99') }}
I'll bet night_led_brightness isn't a string
schedule_start: '22:00:00' schedule_stop: '07:00:00' night_led_brightness: '99'
It is
weird, but ok
it isn't what petro suggested
but you just wrote extra stuff that should be the same
did you fill out schedule start?
I think you have an extra parenthesis too
nope, you don't
schedule_start is set in main variables
right, but it seems like you made it optional
Oh, yeah once you set a time, you can't unset it
But on initial load it will be empty... need to handle that too
Handle it in a separate variable and use the separate variable everywhere
that's what I do
Ok, that's a good idea, I can see in traces what the variable is set to
I'll do input_xyz: !input xyz then later on i'll have xyz: "{{ some code to populate a default when not provided }}"
you gotta dance lightly around reusing a variable
that's why I use input_<var> for all my inputs
that are optional*
I can put in the top under the action: and it should be useable in any condition under it?
put it in the variable section at, that gets executed between triggers and conditions
so it's available everywhere after
like:
action: variables: in_nighttime: '{ eval }'
Any condition farther down in the action block will have access to the variable and it gets set on each run right?
no, in the actual variables section you have defined above everything
Ok
I'm trying to set up an automation to alert me if a sensor on my garage door does not agree with the state coming from the Aladdin (cover) integration. The states never match because the door shows up as open/closed and the sensor shows up as on/off (despite having "show as" garage door)
How can I gracefully write a template that will usually be true, but turn to false if the sensor and the cover disagree?
You could fix the entity for the door from Aladdin so it's a cover
Guessing right now it's a switch
{{ states('cover.aladdin') == states('binary_sensor.garage_door') }} does not work as hoped
{{ states('binary_sensor.garage_door_tilt_sensor_mems') }} // off```
Do you want to fix the entity so it's a cover or fix your automation and leave the entity wrong?
Your tilt sensor is a binary_sensor, so you can force that be a cover if you wanted
Is there some template filter that can "cast" a cover into being a binary sensor or vice versa?
Else just make closed == off and opened == on
@petro Anyway to not run a trigger like this?
- alias: 'NightTime' id: 'NightTime' platform: time at: !input 'schedule_start'
schedule_start: name: Night time LEDs start time description: "LEDs are dimmed or turned off at this time. Scenes will still run. To disable leave at 00:00:00 default." default: '00:00:00' selector: time:
Right now the trigger goes off at 00:00:00 and does nothing...
The solution (a solution):
{{ (states('cover.aladdin') == 'open') == (states('binary_sensor.garage_door_tilt_sensor_mems')|bool) }}
because apparently you can't filter a cover state into a bool
It's already a boolean.
it doesn't behave like a boolean in a template.
That code doesn’t make sense
After today's update, area_name(area) in intent_script began to give the value None.
In the template tool, area_name("some_area_id") returns the correct name.
Has there already been a discussion on this issue?
It makes sense and it works. The cover entity returns open or closed. The binary sensor entity returns on or off. The on/off can be filtered to a Boolean. The cover can't be filtered, but it can be compared to the string 'open' in order to be sort of converted to a Boolean.
Once both entities have been converted into Boolean they can be compared.
Hi! I cannot find YAML files for helpers created via GUI, where can I find them? thanks!
You don't.
so I have to choose between adding in the configuration.yaml directly or GUI and they are not interchangeable?
Correct.
what's the recommended approach here? Once I start with the GUI style I cannot go back?
What do you mean?
You can use both methods, you just can't edit UI-created entities via YAML, or YAML-created entities via UI
perfect, I thought that once you started with GUI you couldn't write YAML and vice-versa. Any quick pros and cons of these methods in your experience?
Some of the UI helpers do not support editing, so you have to delete and recreate.
Some of the UI helpers (like Schedule) lack finer-grain control or additional configuration options that are available via YAML.
The only one that comes to mind as seriously hobbled in the UI is Template.
@haughty breach thank you!
sorry but back on this ``` - name: "Inverter efficiency"
unique_id: "inverter_efficiency"
unit_of_measurement: "%"
state: >
{% set load_power = states('sensor.powmr1_6_inverter_pmr2_load_power') | float %}
{% set grid_power = states('sensor.powmr1_6_inverter_pmr2_grid_power') | float %}
{{ ((load_power /grid_power ) * 100) | round(1) }}
availability: >
{{ states('sensor.powmr1_6_inverter_pmr2_load_power') | float(0) > 0 and states('sensor.powmr1_6_inverter_pmr2_grid_power') | float(0) > 0 }}```
new problem
when solar is being used its reporting numbers above 100% anyway to report values above 100% as just "Solar"
Sorry, what do you mean?
I'd like the state to report numbers above 100% as "Solar" is that possible or does the unit of measurement conflict with that?
That will conflict with the unit of measurement
It will only accept numeric values as state
ok thanks
You can make sure it will always show 100 as highest possible value
think ill play about and make a sum helper to give an accurate value rather than just bodge it
Good morning. I try to get an overview about my solarthermic water heating performance. Of course i could use a physical thermal energy counter, but i am more in to calculating it from the temperature difference in the water storage. Actual i set a start temperature when the pump is starting and an end temperature when the pump stops. Then i use a template
My question now,, is there a more sophisticated way to set the start and end temperature with templates instead of using an automation to set start and end temperature
if that works no point to change it
your other option would be to create template sensors that do the same thing.
how would a template sensor code look like? and how i reset the the calculated value every morning?
Specifically, sounds like you want a trigger-based template sensor if you only want it refreshed at a certain time, this section of what Jorg linked would be an example of that: https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-images-numbers-selects-and-sensors
hey y'all, is there a way to parse the mqtt stream to get a the subtopic?
I guess I still don't get what you mean
you just want to get the subtopic from the full topic?
yes
if you have it, just split it on the / and take the second item
if you provide more context, I can provide an example.
What is meant in the 2024.6 release comment "Limited templates can now be used to disable triggers, conditions, and actions. @farmio thought this might be helpful for blueprint creators." Can we now put logic to disable a trigger?
Yes, put your input into a trigger_variable, then make a second trigger variable to see if it was populated, then use that result to enable/disable the trigger
Next release the validation on the trigger will be ignored if disabled.
Very nice!
How do I use entity-picture as an icon for the template card? I forgot :/
what template card
Mushroom template. It's okay thanks, I figure it out:
{{ state_attr(config.entity, 'entity_picture') }}
Using mushroom template card, can I add a badge icon that shows the current zone (like person card), without manually specifying it?
You need to get the icon from the zone
You mean the icon for the user who is looking at the Dashboard?
Can you elaborate a little bit on this? I was planning on figuring this out this weekend. Like, like how can I get the icon for the current zone for a person entity (assuming that they're actually in a zone and not just Away.)
EDIT: Started doing some research. (Trial and error wasn't working out for me.) Found a post by Didgeridrew that looks like it might get the job done. WTH can’t I pull the zone’s Entity ID via template? #2
hey, Fes, most of the other vets seem to be afk, and I hope you might know the answer to this
I have an automation that has a template condition, but apparently for: doesnt work. How would I get that to work, if it can be done?
make the template into a binary sensor, and for: the amount of time it has been on with a state condition
I dont think I can, as it's dependent on the trigger
```{{ is_state('binary_sensor.'~trigger.topic.split('/')[0]~'_person_occupancy', 'on') }}"````
you can get the state object for the template binary sensor, and check the last_changed time
if you want to see if it's been in the on state for > N minutes
ok so I know what your saying, but I could use a nudge on how to do that
Please Help me with this
hello, all, I currentl have this part in my automation that calls Google to describe a photo, and it works really well:
- service: google_generative_ai_conversation.generate_content
data:
image_filename: www/bird_feeder/blink_camera_still_image.jpg
prompt: >-
Name the type of bird in the photo. If there is no bird, just say there
is no bird. Do NOT use special characters in your responce like
asterisks *
response_variable: generated_content
and the tts part:
- service: tts.speak
data:
cache: true
media_player_entity_id: media_player.fire_tablet
message: >-
Motion has been detected at your bird feeder. {{ generated_content.text
}}
target:
entity_id: tts.piper
the problem is sometimes the sevice to google fails because of a 500 error and the automation stops
how can, for example, make that if the call fails, it says some generic message like "motion has been detected" instead
Motion has been detected at your bird feeder. {% if 'text' in generated_response %}{{ generated_response['text'] }}{% else %}There was a problem{% endif %}
oh that is good!! better than what I was about to do below...thank you
like this:
message: |-
{% if (response_variable: generated_contente == 'true') %}
Motion has been detected at your bird feeder. {{ generated_content.text }}
{% else %}
Motion has been detected
{% endif %}
Could probably put it into a one-liner using iif as well, but either way should work.
yours works, thanks 🙂
so that I get th syntax right, something like this:
- service: tts.speak
data:
cache: true
media_player_entity_id: media_player.fire_tablet
message: >-
{% if 'text' in generated_response %}
Motion has been detected at your bird feeder. {{ generated_response['text'] }}
{% else %}
Motion has been detected at your bird feeder. No AI avialable.
{% endif %}
target:
entity_id: tts.piper
Yup. That should do it. You can test it in the Template editor (Developer Tools > Templates) as well.
{% set generated_response = {'text': 'Test' } %}
{% if 'text' in generated_response %}
Motion has been detected at your bird feeder. {{ generated_response['text'] }}
{% else %}
Motion has been detected at your bird feeder. No AI avialable.
{% endif %}
You can set different values (or just comment out the first set line) and see how it works.
oh, cool, i tested as is and then just removing the Test word (leaving '') and it worked as described. Cheers bud
I could use some help with timedelta() and a last_changed time to see if it's greater than a value
use case: if the time delta of last changed and now() is greater than 10 sec
That will not be very accurate since now() is limited to only update once a minute
if it's in a repeat until loop, wouldnt it keep checking?
Than it probably works
templates are only triggered by now once per minute, but if the template is already evaluating now() will be perfectly accurate
hmm ok, this seems to always default to else even though it the AI gave a valid responce. For example, a valid responce from the the AI would be:
text: |
Red-winged Blackbird
I'll have to catch what an invalid responce looks like
ok,. so I found the solution to my problem, so now the question is how would I get that in a template?
I've been fiddling with a couple options that I dont think are what I want
{{ now() - timedelta(seconds=10) > states.xxx.yyy.last_changed }}
Hi, what's the easiest way to make something singular when the state value is 1 and all other values its plural?
{{ iif(states('sensor.master_bedroom_average_temperature')|int > 1, "states", "state") }}
Something like that should work, but there are probably other ways too.
ok ... last one ... I hope
shouldnt this return True if the payload is 1? or do i need to | int it?
- condition: template
value_template: >
{{ trigger.payload = 1 }}
You have to cast it to int. IIRC, all payloads are strings by default.
aight
But you would need two equal signs, not one. Two compares, one sets.
ahh good catch
lol totally missed that too.
been messin with this fin thing all day
Welcome to HA, where time passes 100x faster
lol
ehh .. more of a frustration at this point
at least this last little bit
Im missing something in this frickin automation I rewrote today
What’s the automation? I’m too lazy to scroll up lol
hold please
plays hold music
This hold music sucks. It's been going on for like an hour
Support at its finest 🤣
lol
"Welcome to the zoological emergency hotline. Please hold the lion!"
dad jokes all day
so I think I've found part of my problem in the automation concerning the template
repeat, until condition 1 or 2, which 2 is {{ now() - timedelta(seconds=states('input_number.frigate_'~trigger.topic.split('/')[1]~'_timeon_duration')|int) > states['binary_sensor.'~trigger.topic.split('/')[1]~'_person_occupancy'].last_changed | as_local}}
the thought was that now() was being evaluated in the repeat loop until it was true
I dont know for absolute certain, but I dont think that is the case
Hey team, is there a way to define a sensor but have its resulting options show up in the automation screen? currently have this but when I open it on automations I can only see "Any state", "Unavailable" and "Unknown"
- name: "Living Room Roller Status"
state: >
{{ 'Open' if is_state('input_boolean.roller_shutters_living_room', 'on') else 'Closed' }}
No, not with a template sensor. But you can just type whatever you want there
the automation GUI only shows those states for entities for which it knows the possible states
instead of creating a sensor, you could consider creating a binary sensor witih device_class: window
that will show as Open or Closed on your dashboard, and in the automation GUI as well
- binary_sensor:
- name: "Living Room Roller Status"
device_class: window
unique_id: binary_sensor_roller_shutters_living_room
state: >
{{ is_state('input_boolean.roller_shutters_living_room', 'on') }}
or binary_sensor.door in case if the shutters are for a door
Hey everyone, i've been getting a lot of good help from Tinkerer about creating a template but i need a little more help. I'm trying to create a template to get the GPS coordinates of my car using PSA Car Controller. This pulls information from Vauxhall into a json file which i want to extract the GPS information from. the template looks like this;
sensors:
corsa_e_latitude:
friendly_name: "Corsa E Lat"
value_template: '{{ states.sensor.corsa_e.attributes["last.position"]["geometry"]["coordinates"]["0"] }}'
corsa_e_longitude:
friendly_name: "Corsa E Long"
value_template: '{{ states.sensor.corsa_e.attributes["last.position"]["geometry"]["coordinates"]["1"] }}'```
After restarting HA its showing as unavaliable still... the json has this "last_position": {"type": "Feature", "geometry": {"coordinates": [-1.21465, 54.55443, 29.0], "type": "Point"
I think ["0"] and ["1"] should be [0] and [1]. They are list indexes, not keys.
Okay great i'll ammend the yaml and restart, see what happens
I think i've had enough of [0] vs [1] for this week
lol
Still showing as unavaliable 😦
In the log its showing ```Logger: homeassistant.components.template.template_entity
Source: components/template/template_entity.py:197
integration: Template (documentation, issues)
First occurred: 12:37:15 (2 occurrences)
Last logged: 12:37:15
TemplateError('UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last.position'') while processing template 'Template<template=({{ states.sensor.corsa_e.attributes["last.position"]["geometry"]["coordinates"][0] }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.corsa_e_latitude'
TemplateError('UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last.position'') while processing template 'Template<template=({{ states.sensor.corsa_e.attributes["last.position"]["geometry"]["coordinates"][1] }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.corsa_e_longitude'
homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last.position''
Ah, so the json isn't coming back with that property then.
Thank you! didnt realise I could just plain type what I want - currently going to leave it as is to save me having to stuff around with other things but thank you!
@past beacon make sure you are pulling the right key from the JSON ... 'last.positon' doesnt exist
Funny as i can see it! It has last_position: type: geometry: coordinates: 0: 1: 2:
oh feck
! _ not .
lol
last_position is not the same as last.position
lmao... that would do it.
"it's the little things"
Such a noob!
you might want to use state_attr()
and apply some failsafes in case the entity is not available
or an availaility_template
and you might want to consider using the modern template sensor format
ok y'all, it's time for a coffee. 🙂
I'm so new to this i'm being guided by others currently...
no worries
what you have now is the legacy format
So i've corrected the typo and im still getting the error in the logs ```Logger: homeassistant.components.template.template_entity
Source: components/template/template_entity.py:197
integration: Template (documentation, issues)
First occurred: 12:43:55 (2 occurrences)
Last logged: 12:43:55
TemplateError('UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_position'') while processing template 'Template<template=({{ states.sensor.corsa_e.attributes["last_position"]["geometry"]["coordinates"][0] }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.corsa_e_latitude'
TemplateError('UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_position'') while processing template 'Template<template=({{ states.sensor.corsa_e.attributes["last_position"]["geometry"]["coordinates"][1] }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.corsa_e_longitude'
some advice regarding template sensors:
- add a
unique_id. This will give you the option to change name and entity_id in the GUI, but it will also prevent that double entries are created, and you end up withsensor.corsa_lattitude_47 - add an
availabilitytemplate which will prevent errors in your log
did you restart your system?
Yes you can see the error changed to last_position
do the template sensors have a valid state now?
(the longitude and lattitude of the car)
No still showing as unavaliable
test your templates in devtools > templates
that's also a general advice, first test them there until they work, then start creating the config
if you only have a template for the state, you don't even need yaml configuration, you can just create a template helper
So using the template helper (great advice) i'm getting the same error UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_position
are you sure the entity_id is correct
@past beacon I converted your message into a file since it's above 15 lines :+1:
sensor.corsa_e_latitude
Corsa E Lat
unavailable friendly_name: Corsa E Lat
sensor.corsa_e_longitude
Corsa E Long
unavailable friendly_name: Corsa E Long
@past beacon I converted your message into a file since it's above 15 lines :+1:
Hi, I'm trying to do a helper that calculates the electricity bill for the current period.
I don't see a last_position attribute there
I have the - last_position in the json section... i'll try restarting and see if the sensor picks it up
There its now... maybe the restart picked it up
you could probably have reloaded REST in developer tools > YAML
but okay, a restart works as well
anyway, do your template sensors work now?
Yes they are there now... in terms of the ID do i just add that into the Yaml?
{{ (state_attr('sensor.corsa_e', 'last_position') | default({}, true)).get('geometry', {}).get('coordinates', [])[0] | default('unavailable') }}
this template will prevent errors when the REST sensor is unavaiable
Do i create that in settings/helpers?
replace [0] add the end with [1] for longitude
you can just use that template in a template helper yes
@past beacon I converted your message into a file since it's above 15 lines :+1:
does the device tracker work?
if so you better ask in #frontend-archived on how to display it properly on the map
I have two timestamps I've generated using helpers and I want to compare them to have a conditional piece of text to display in a card. Do I need template conditions for this or can I use template expansions in something else?
@glad gust I converted your message into a file since it's above 15 lines :+1:
you can't use templates for conditional card
so how do I build a conditional based on two state values?
make a template sensor, condition on that
as a general rule frontend never supports templates as that would require it to constantly ask the backend to re-evaluate them every time you navigate or reload the page.
ok so I need to create a boolean sensor that encapsulates the test?
cards:
- type: conditional
conditions:- condition: state
entity: sensor.hot_water_ready_2
state: 'True'
card:
type: custom:mushroom-template-card
primary: |
Hot Water ready since {{ input_datetime.hot_water_available_since }}
secondary: ''
icon: mdi:shower
badge_color: green
fill_container: true
- condition: state
I can see the state is true but the text doesn't show... hmm but the card does
That's not how you retrieve the state for an entity
More docs are in the channel topic
hi all, if the responce to a sucessful service call is this:
text: |
responce text
would this if/else capture it?
{% if 'text' in generated_response %}
Motion has been detected at your bird feeder. {{ generated_response['text'] }}
{% else %}
Motion has been detected at your bird feeder. No AI avialable.
{% endif %}
it seems to always default to else as is above.
I'm not following that
what does the first part mean?
responses are stored in a variable that you define
I don't see the relationship between your first code block and generated_response that you're using in the second
{% set generated_response = {'text': 'foo'} %}
{{ generated_response['text'] }}
{{ 'text' in generated_response }}
foo
True
does that help?
its a google request, sometimes there are 500 errors, I don't how its looks like when it fails, it might be blank. But when it successful, thats what what first block looks like
its always text: |
plus whatever generated text below
That's weird. I never have had issues with that catching 500 errors.
After I updated yesterday to: Core
2024.6.0
Supervisor
2024.06.1
Operating System
12.3
Frontend
20240605.0, I have lost all my generic thermostats. The are located inside my climate.yaml. Have I lost some breaking changes or is there anything else wrong? EDIT: A restart solved the problem.
let me check, it works in the template editor
but when its in the automation, it does not work
@floral steeple I converted your message into a file since it's above 15 lines :+1:
it does not, it just defaults to else even when there is no google error
Do me a favor and post your script again? I can't find it up there ^^^
hence, I don't think it catches a proper responce, i.e.
text: |
responce text
ok one sec
the objective is this: when Google give a 500 error, it just defaults to to the message "Motion has been detected" , but if google is up and running, the message is "Motion has been detected. The bird is...."
Yeah, that's what I have basically. Works pretty much every time without issue: https://dpaste.org/7TwDx
let me try it exactly as you have it without lines and spaces.
if I wanted to add something to the work ing google messags, is it like this?:
{% if 'text' in generated_response %}Motion has been detected {{ generated_response['text']
}}{% else %}Motion has been detected.{% endif %}
Yup
interesting. can you manually run yours? even if I use your exact lines:
{% if 'text' in generated_response %}{{ generated_response['text']
}}{% else %}There was a problem{% endif %}
it always defaults to there was a problem. But, google did respond with an answers looking at automation traces
Sure. One sec.
I don't think the problem is in your template
I think I see the issue
you should use if 'text' in generated_content.generated_response
proper google responce, but still defaults there is a problem
Your response variable is generated_content and you are not using that
Mine doesn't have a nested generated_response in generated_content.
Ohhhhhh... wait... yeah, now I see it.
You should at least use generated_content
I completely missed that
i missed everything 🙂
lol
so should be this:
{% if 'text' in generated_content.generated_response %}{{ generated_response['text']
}}{% else %}There was a problem{% endif %}
No
{% if 'text' in generated_content %}{{ generated_content['text']
}}{% else %}There was a problem{% endif %}
You named your variable generated_content, not generated_response
You could also rename your response_variable
They just need to match
hey guys, someone knows why this template dont showing an entitie?
{% for state in states.climate %}
{%- if state.entity_id | regex_match("climate.*_klimaanlage", ignorecase=False) and state.attributes.hvac_modes in ['cool'] -%}
{{
{
'type': "tile",
'entity': state.entity_id,
'name': state.attributes.friendly_name.split(' Klimaanlage')[0]
}
}},
{%- endif -%}
{% endfor %}```
when i remove "and state.attributes.hvac_modes in ['cool']" it works but than it shows all
Attributes on Helpers
Your comparison is backward. Your code is asking if there is a list of HVAC modes in ['cool']
Test the statement in developer tools:
'cool' in state_attr('climate.my_climate_entity, 'hvac_modes')}}
thank you for your reply, i already fix it 😉
and state.state in ["auto", "cool", "heat", "dry"] -%}
Yeah, the original wasn't very useful anyway. The list of hvac_modes never changes
yeah thats correct, i realized that a little bit later too ^^
Anyone able to clear up my understanding of this
- name: "Essentials Battery %"
unique_id: essentials_battery_percentage
unit_of_measurement: "%"
device_class: battery
availability: "{{ states('sensor.powmr1_6_inverter_pmr2_battery_voltage')|is_number }}"
state: >
{% set batt_volts = states('sensor.powmr1_6_inverter_pmr2_battery_voltage')|float(0) %}
{% set max_battery_voltage = 12.6 %}
{% set min_battery_voltage = 10.0 %}
{% set batt_pct = (batt_volts - min_battery_voltage) / (max_battery_voltage - min_battery_voltage) * 100 %} {# calculate percent from the voltage #}
{% set batt_pct_clamped = ([0, batt_pct, 100]|sort)[1]|round(0) %} {# clamp the output to a 0-100% range #}
{{ batt_pct_clamped }}
So if the output range is clamped the sensor won't show above 100% correct? So even though the sensor might read 13.6v I shouldn't get any errors or values above 100%?
Yes the template will always output a value from 0-100 inclusive
Found an easier way to extract zone icon, just need to obtain the right colour now:
{{ state_attr("zone."+states(entity),"icon") }}
I'm guessing it's only possible using card_mod?
@steady flower I converted your message into a file since it's above 15 lines :+1:
@steady flower I converted your message into a file since it's above 15 lines :+1:
Never mind. Second one worked. Had to do a full restart not a Yaml reload.
How do I add multiple if statements together? elifs?
--main-color: green !important;
{% else %}
{% if states(config.entity) == 'work' %}
--main-color: blue !important;
{% else %}
--main-color: orange !important;
{% endif %}```
I also tried with elifs, but it ignores the work state in the code and uses else statement instead, must be doing something wrong:
{% if states(config.entity) == 'home' %}
--main-color: green !important;
{% elif states(config.entity) == 'work' %}
--main-color: blue !important;
{% else %}
--main-color: orange !important;
{% endif %}```
Are you sure that's what states(config.entity) is returning as it's state?
It should be pulling the zone state from the entity, home works perfectly fine
I'd double check the state first and see if it is actually returning work. The template syntax is spot on, so I don't think it's an issue there.
Yeh thanks, I think you're right. I'm using {% elif states('zone.work') %} now, and it works great
Woot. 🙂
Originally, I tried the method that you described, but I noticed if the zone friendly_name for the zone contained special characters, then it would not match the entity. For example, say you have a zone called "Grandma's House", this won't match (because of the apostrophe and space) but something simple like "Grandma" probably would.
I was working on this the other day and this is what I came up with to get around the special character matching.
{{ states.zone | selectattr('attributes.persons', 'search', 'person.derek') | map(attribute='attributes.icon') | join }}```which returns `mdi:home`.
Note: In this example, I hard-coded the person entity, but you could just as easily use a variable in its place. I also don't know if it will work properly if two people are in the same zone.
Hey guys. How can I create a template switch using scenes or scripts? I'm having trouble because neither scenes nor scripts seem to have an on state.
Ummm... hmmmm 🤔 not sure. What are you actually trying to do?
I'm trying to make some buttons that will change a scene from one to the other. I know how to do that, but I'd like for the buttons to show on or off, whenever the scene entity members are in the correct state. The only thing that I could think of was template switches.
I had the same problem with a multi speed fan, but I overcame that, because the fan speeds were a combination of actual switches.
Maybe just store the current scene in an input_text helper?
^ that's basically what I was thinking. have your script/scene set the helper. The problem you're going to run into is when you "change" to something other than the scene. (Like you turn a specific light off and are technically not "set" to that scene.)
Hmmm, I'd never thought of that. I'll have to look into it.
I know that I could make the template switch using every member of the scene separately, in it's correct state, but that's overly cumbersome.
Yeah, that's gonna be a mess and you're going to rue the day you write it. 🙂
Yeah, that's why I'm not gonna...lol
I wonder why scenes and scripts aren't meant to have an on and off state. That would be easy. If all of the members are in the correct state, the script or scene would be on and off, if all of the members aren't in the correct state.
scenes have been stateless for a long time. There was a decision for it, but I honestly don't remember what the reason was.
I imagine it is because of the amount of checks HA would have to make to look at every little thing in a scene to determine if it matches. Is the light on, set to a certain color_temp/color, brightness, etc? It's probably not worth the processing cycles for something that may rarely return true.
Possibly... There was an answer for it on the forums, but I'm too lazy to go looking for it now lol
It's really weird to me, to be able to turn on a scene with a service, but the scene not having an on state. Although that's ultimately irrelevant, because I didn't invent the coding language...lol.
Yeah, most other platforms do have stateful scenes and there's a lot of angst about this on the forums as well, but it's the world we live in. 🙂
How would I use the input_text method?
Create an automation that if the scene is activated, set an input text or boolean to on?
That's one way. Could also do something like create a template sensor that looks at the last triggered time for a scene and if in the last few minutes, consider it on. Oh, have a script that the button calls and gets/sets the input_text helper there (rather than calling the scene directly).
The last way is probably best.
That's what I'm thinking.
can anybody see why this is not working?
"specified_start_date": "{{ states('input_text.roller_selected_date') }}"
}```
if I put the date in manually instead of using the template it works great. but using the template, the AppDaemon python says its getting None
Well what does the {{ states('input_text.roller_selected_date') }} output in the template section of the developer tools in HA?
I doubt that templates are evaluated there
Then the thing where you're putting the whole template is not happy.
yeah i was hoping that home assistant would convert the template into the string and pass that over
how would i do that do i need to make a script?
There is no service for that event
Right so I guess i should make a script that fires the event
is that what you mean
yes
Okay thanks will try that 👍
Yep worked straight away. Thanks a lot. much appreciated. Sure wish i asked a couple hours ago 🤦♂️
Can i use the members of a switch group as an automation trigger?
i.e.:
trigger:
- platform: state
entity_id:
- "{{ expand('switch.day_lights') | selectattr('domain', 'eq', 'switch') | map(attribute='entity_id') | list }}"
or
entity_id: "{{ expand(state_attr('switch.day_lights', 'entity_id')) | map(attribute='entity_id') | list }}"
any ideas? I have an automation that follows the state of a group, and it works ok. I want to also trigger the automation when a switch in the group changes state (the group stste doesn't change), is that possible without listing all the entities of the group manually?
You could create a template sensor to count how many switches in that group are ON, and then trigger your automation when that template entity changes state
I'm trying to build a template, if my device_tracker status = away, then it should output at my dashboard for how long I've been away. Just like the logbook does.
June 10, 2024 Was detected away 07:14:03 - 6 hours ago
What would be the correct way of doing this? Using history_stats?
last_changed attribute won't cut it.
last changed does it
{{ relative_time(states.device_tracker.xyz.last_changed) }}
@stiff minnow ^
Hmm, last_changed doesn't give me the correct info of when status home changed to not_home
did you see the template?
last_changed is the correct info
keep in mind that it will reset after a restart.
Hmm, sorry if I'm mistaken but that template gives me the minutes since the status of my device_tracker last changed. Not when home changed to not_home (as in Logbook)
I mean, {{ relative_time(states.device_tracker.xyz.last_changed) }} won't help me if I wanted to know for how long I've been away from home.
that depends if you use other zones as well
if you only have a zone.home the last_changed timestamp will be the one of the change to home or to not_home depending on it's current state
so if the current state is not_home, the template petro provided will be the time you were away
yeah, that's why I mentioned the usage of other zones, it won't work if you also have a work zone and you've been in that zone
but maybe @stiff minnow can shed some light on that 🙂
Hehe yeah, I only have zone.home
then the template from petro will work
not sure why you think it won't
if you only have zone.home the only 2 possble states of your device tracker are home and not_home
so when you are away from home, the last_changed timestamp will be the state change from home to not_home
Ok, so the output of that template currently when I'm not_home is 8 minutes.
Looking in the logbook
MY-DEVICE-XYZ was detected away 07:14:03 - 6 hours ago
yes, did you restart 8 minutes ago?
Nope
look at the history of the entity then
because something occurred 8 minutes ago that caused the state to change
last_changed is the last time the state of the entity changed
Yeah, status seem to change, state is still away (not_home) though
what do you mean "status"
the state changed or it didn't
status isn't a thing in HA
Yeah sorry, I'm quite new to HA.
State is not_home
right, so last_changed shows the last time the state changed
so something happened 8 minutes ago that caused your state to change
you keep telling me that nothing happened, but that's not possible because last_changed will show the last time the state changed
so you're either unknownlingly lying, or incorrect about the state changing
go to the history of your device tracker and look at it, if you see any vertical lines in your bar graph, that means the state changed at that point
Thanks for clarifying.. the vertical graph changed at 07:14 to grey (away) and its still the same color.
there's a state change inbetween. A sliver where the state was something other than away for a small moment.
use the history to zoom in on that timeframe to see what the state did.
Can I possible to upload a prtscrn to clarify?
you can use imgur
I don't see a need for the clarify, if you have a line between 2 away states that means the state changed momentarily from away to something else ,then back to away
ok, then last_changed is what you want to use
what does last_changed show in the template editor?
with the provided template
26 minutes currently
can you share a screenshot please
it does show 23 minutes at the top of the more info screenshot as well
that graph filters out state changes because of restarts though
Yeah, no restarts
or HA restarted without user action 🙂
Fes, your work around comes to mind: https://community.home-assistant.io/t/persistent-version-of-last-changed-for-the-ui/467163/66?u=burg93
that won't work if his state is changing
Oh
It didn't, then it keeps on restarting pretty much every minute 🙂
it filters out state changes from and to unaivalable and unknown
well, last time would be 23 minutes ago
If that's from the mobile app, it seems to update the last_updated on check in from the app. I just checked mine (and I haven't moved from my desk for over an hour) and it says 4 minutes ago.
last updated is not the same as last changed
last_changed = last time state, literally only the state changed
last_updated can be coordinates which updated (a bit)
last_updated = last time the whole state object (state and attributes) updated
then there's a bug in whatever integration is doing that
is that on Android?
Companion app.
which one
Nope. Mine is iOS.
I just did a restart, so I can't check
Mine is Android
But it will be on my desk for the next hours, I will keep an eye on it
Same thing for the companion app on my iPad as well.
And I haven't touched my iPad (nor has it moved) since yesterday morning.
Yeah, if I check the template on my person entity, it comes back correctly.
So might just be something with the device_tracker itself.
Same here I guess, I it says 1 hour in my case
1 hour since I restarted HA
Anything else you want me to check?
there's nothing else to check
your options are to use last_changed
You can make an automation to set another entity when it goes from home to away
like an input_datetime
Alright alright, thanks
I just created this sensor...
- name: Internet Connection Failed Recently
device_class: problem
state: >
{{ is_state('binary_sensor.8_8_8_8_ping', 'off') }}
delay_off: 00:10:00```
but it is showing as unavailable in the dev tools
The delay_off is ten minutes. so does that mean i have to wait ten minutes for its first initial state to work?
because thats the only thing i can think of
it'll be unknown until then, not unavailable
Yeah I think it probably was unknown it's now working. Thanks 🙏🏼
my device tracker last_changed wasn't even affected by the last restart so it seems
as it is from before the last reboot
oh wait
first one is UTC
so it changed 5 minutes ago, that's not correct, it has been on my desk for at least the last 2 hours
So also for me there seem to be unexpected updates to last_changed
Oh
not sure why you're saying 'Oh', said this hours ago already
Sorry, you won 😉
nothing to win, thought we moved on
fes was just updating his findings and i was replying to him
I just wanted emphasize @marble jackal findings, since it became obvious for me what actually was going on
When doing state_changed triggers with covers, does everyone just accept you will get a ton of trigger events as it opens/closes? Or do you rate limit it?
state_changed events aren't rate limited
I know
I guess I don't get the question then
If you have a state_trigger on a cover (like a garage door), it will fire 20-30 times as it opens and closes. This can be noisy and if all I care about is opening/closing/open/closed and not each percent closed.
that will only happen if attributes are changing, like position
RIght
if your cover doesn't support position you only get normal state changes
if you only care about on-off etc, then add a condition to check that for that specific trigger
you can't filter state change events to only look for on/off
I have that, but it still fires and you get a trace
right
Ok, just checking
What's a more effecient method to look for state changes?
a normal state trigger
How is that different than this:
- platform: event event_type: state_changed event_data: entity_id: '{{ inputs[4].trigger_entity }}' id: 'StateTrigger' alias: '4'
and you're using a template because the trigger entity is templated?
Yes
Guess I could check old state vs new state and if state is the same, then don't do anything
But it doesn't stop it from firing, so really doesn't help much
Would save traffic on the Z-Wave network from firing 3 messages a second per device.
zwave isn't creating the state changed events
those are created naturally by HA
when a state changes
I've seen that some cover integration docall intermediate state changes to update the inbetween positions, so it can be that Z-wave does this also
Yeah, my triggers change LED on a Z-Wave scene controller
that's just the behavior of that command class in HA, but zwave isn't creating the state changed events. The events are created by the core HA integration. It's just reporting that it saw a change and that event is being raised.
so, zwave -> update entity -> ha report change
Yep
not exactly what you said, but taking your idea I came up with this:
trigger:
- platform: template
value_template: "{{ expand('switch.day_lights') | selectattr('state', 'eq', 'on') }}"
seems to work so far... I dont really need the count or a map or list just that it changed.
I doubt that's doing what you think it's doing
Automation template Triggers will trigger when they transition from false to true. So no matter what your template outputs, it will be converted to true or false
it returns a generator, and that will always be true
add | list | count > 0
true. its working in the sense that it changes, but its not doing what i think its doing. I guess it needs a sensor and trigger on state of sensor.
then again, if thats a switch group, just use the switch group with a normal state trigger
0 won't work because i want it to trigger when some are on, and a new switch turns on, which won't trigger on a groups state.
then a template trigger won't work either
i realised. 😦
just list out the entities
That's why a sensor with the current count and a state trigger based on that was suggested. But then it's a pain to get which one changed, if you care about that
List the ones which are on in an attribute. Then you can compare the from state and to state to get the one which caused the state change
But that could be considered a pain maybe
We really just need a friggin group trigger already
Maybe an expand option on the state trigger
This comes up enough to warrant it
it's a common request and the people requesting this functionality would have no idea how to do it
I wrote up a solution at some point that would benefit from a template blueprint
how to use list in template with containe the string
{{ ( ['text1','text2'] in generated_content_bep_watching_tv.text ) }}
Now i use :
( ( 'text1' in generated_content_bep_watching_tv.text ) or ( 'text2' in generated_content_bep_watching_tv.text )
{{ generated_content_bep_watching_tv.text is search('text1|text2') }} should work
it uses regex, and in regex the | is or
thanks
I need help with the Scrape Template, I want to get the gas calorific value from my gas supplier to better calculate the cost and estimated kwh. But I dont know how I would get the info from the page, I dont see anything thats unique and this specifi point
also I need to get the 11th element in a list because this is the newest value
can I filter with the value of an headline element?
service: chime_tts.say
target:
entity_id:
- media_player.kitchen
- media_player.dining_room
data:
chime_path: bells_2
message: The washing's done!
tts_platform: amazon_polly
tts_speed: 150
Is there a way to build that multiple entity_id using a template? I have a group that each member has attributes of media_player devices and I want to use that as multiple entity_ids
Yes, the group does not contain the media player devices themselves. It contains satellite devices which each contain attributes which includes media player devices. Further, I want to be able to pull another attribute for do not disturb mode so that only satellites not in do not disturb mode will receive the announcement.
by pull I mean filter the group using the template for satellite devices which are not in do not disturb mode and return those media player devices
Ahhh, ok. That gives a bit more context. Hold on, let me absorb that for a minute.
yeah it's a bit obtuse for sure.
lol, tbf, you never have simple questions... sooooo 😉
haha.. Thanks I guess! 😉
(That was a compliment) 🙂
Okay so you need to compile a target list from a group entity, that has satellite entities as members, which have an attribute with the actual needed media player?
Right. I kind of have that already but I don't know how to pass it to the service call.
Seems doable with a for loop and a namespace
I don't know what that means unfortunately or how to accomplish
I guess this should work
{%- set ns = namespace(targets=[]) -%}
{%- for satellite in expand('group.my_group') -%}
{%- if not state_attr(satellite.entity_id,"do_not_disturb") -%}
{%- set ns.target = ns.target + state_attr(satellite.entity_id,"mediaplayer_device") -%}
{%- endif -%}
{%- endfor -%}
{{ns.targets}}
But I think you also need to move entity_id from target to data to allow templating the entity_ids
@bronze prawn if you test this in the devtools it should return a list of media_players
{%- set ns = namespace(targets=[]) -%}
{%- for satellite in expand('group.viewassist_satellites') -%}
{%- if not state_attr(satellite.entity_id,"do_not_disturb") -%}
{%- set ns.target = ns.target + state_attr(satellite.entity_id,"mediaplayer_device") -%}
{%- endif -%}
{%- endfor -%}
{{ns.targets}}
This produces an empty list. I took out the nested if statement to see if I'd get back anything and it is still empty
Ah I see, made some small errors
{%- set ns = namespace(targets=[]) -%}
{%- for satellite in expand('group.viewassist_satellites') -%}
{%- if not state_attr(satellite.entity_id,"do_not_disturb") -%}
{%- set ns.targets = ns.targets + [state_attr(satellite.entity_id,"mediaplayer_device")] -%}
{%- endif -%}
{%- endfor -%}
{{ns.targets}}
Thanks for this. Still empty though
Just a empty list? No errors?
right. just []
Than it can be that the attributes names are not correct
hmm.. I should have checked that. Let me double
@bronze prawn I converted your message into a file since it's above 15 lines :+1:
grr.. sorry. Here's the attributes for one of them in the list
Could it be the way I am assigning false to do_not_disturb?
Yeah if it’s not a real boolean
so it's just text
You can check that by removing the if statement
Yeah that produces a list. Can you modify so that it checks for the string is either false or not true? Which ever
{%- if state_attr(satellite.entity_id,"do_not_disturb")=="false" -%}```
right?
Yup that checks for equal normal text(string)
got it. And I can then just pop that in for device_id and it should populate that list which is acceptable, right?
Yes but IIRC you also need to do this
I am not sure if things under target are templateable
Just tested. Works great! Thanks so much for the help. I will be able to use this for a few different things. Appreciate you!
FYI without namespace {{ expand('group.viewassist_satellites') | map(attribute='entity_id') | select('is_state_attr', 'do_not_disturb', 'false') | map('state_attr','mediaplayer_device') | list }}
They are
@fallen hill I converted your message into a file since it's above 15 lines :+1:
So what I nerver really understood is how I would create a sensor which uses for example. My Gas Meter and tracks it for a year but only the difference of this.
How can I reset a value after a year? 😄
I want to predict the estimated gas consumption of this year haha
@fallen hill If the template switch changes state because of the output of the value template, the actions for turn_on or turn_off are not performed
@gaunt remnant sounds like you want a utility meter
hmm okay, I guess the cron would be "0 0 1 9 1" for a reset on September 1st?
Not sure about that, but you can also not set an automatic reset, and reset is using an automation on September 1st
seems to be working
`Source
sensor.tibber_verbrauch_auf_der_letzten_meile
Status
collecting
Last period
0
Last valid state
4457.24489923
Cron pattern
0 0 1 8 1
Next reset
- August 2024 um 00:00:00`
post what you've tried
but it tells me i'm missing mushroom-slider-card, but i don't find it anywhere
@TheFes any advice on how to make it work? Can this only be achieved with an automation?
this is a #frontend-archived question, not #templates-archived
Yes, you need an automation for that
beep
bot took over account?
negative
that's what a bot would say
don't get me wrong i'm aussie but if I make a mum joke is that what a bot would say
if it's a cheeky and fun bot, yes
been away for a while moved house and now have more stuff to automate, did the macros take that's about when I left.
cheeky would be polite but that's not #templates-archived
Interesting, thanks for sharing. I'm guessing this could be a reason why I'm having issues with zone names disappearing? Although, it disappears randomly even with zones without any special characters. (i.e Work). This is what I'm using to pull the current zone:
{{ state_attr("zone."+states(entity),"friendly_name") }}
if the returned value of states(entity) is uppercase or doesn't match your object_id, then the template will fail.
also, what is the entity in question?
I'm trying to retrieve the current Zone for each person using a template card. It does work at times, but from what I had gathered, it disappears when the zone changes?
{% set zone_name = states(entity) %}
{% set person = states.zone | selectattr('name', 'eq', zone_name) | list | first | default(None) %}
{{ person if person is not none else zone_name }}
not sure why you're doing that though because the state of the person will be the zone friendly name
i.e. there's no point to do what you're trying to do
when you can just use {{ states(entity) }}
This way it displays unfriendly names, no? (not_home)
that will display home, not_home, and Zone Friendly Name
Sorry maybe, I hadn't explained it clearly. Basically, I'm using the Person card for each person using the template card, and want to display their current zone, i.e (Home, Work, Fargo's etc)
then use {{ state_translated(entity) }}
Oh wow, thanks! God knows why I over complicated this to begin with. 😅
that's why we always talk about the XY problem
The XY problem is asking about your attempted solution rather than your actual problem.
this right here is a perfect example of it
Tbf, I used the code posted by someone on the forums, which looks to be outdated
state_translated was introduced 'recently'?
maybe a few months ago
regardless, that template was destined to fail because the state of a person can return the zone friendly name
and entity_id's like this zone.My Place Of Work are not valid entity_ids
Ah, good to know. appreciate your help
How would you define 'Away' state since it's not a created zone? I'm using something similar, but couldn't find a way to show away icon
away is not_home
you can check 'under the hood states' in developer tools -> states page
Something like this?
--main-color: blue !important;
{% elif states(config.entity) == 'not_home' %}
--main-color: red !important;
{% else %}
--main-color: grey !important;
{% endif %}
I'm using this for badge_icon:
badge_icon: '{{ state_attr("zone."+states(entity),"icon") }}'
where is everyone getting that shitty template from?
that's the second time i've seen that today
icon is no longer an attribute
well anyways, your template should be
{% set home_icon = 'mdi:home' %}
{% set away_icon = 'mdi:home' %}
{% set unknown_icon = 'mdi:home' %}
{% set items = dict(home=home_icon, not_home=away_icon) %}
{% set zone = states(entity) %}
{% set icon = states.zone | selectattr('name', 'eq', zone) | map(attribute='attributes.icon') | list | first | default %}
{{ icon if icon else items.get(zone, unknown_icon) }}
that's a lot of home icons
just fill out your home, away, and unknown icon and the zone icons will just fall in place
it mimics what HA does
could be an even simpler template 🙂
Finally solved, thank you so much!
does badge_color only support basic rgb colours?
I'm guessing I have to use card_mod for css ones?
that's a question for #frontend-archived
Ah sorry, thanks
Is there a reason a template would show in developer tools when accessing HA from the local up address but now show up when accessing from nabu casa?
You mean persistent in the window when accessed different ways?
They're different sites as far as the browser is concerned
Trying to get a percentage value comparing today and yesterdays energy. I am doing something wrong in this template? It's unavailable, despite a restart
- name: Energy Daily Difference
state: >-
{% set today = states('sensor.energy_day_fronius_inverter_1_192_168_68_113') | float %}
{% set yesterday = state_attr('sensor.symo_energy_day_utility_meter', 'last_period') | float %}
{{ ((today / (yesterday / 24 * now().hour) - 1) * 100) | round }}
unit_of_measurement: "%"
actually partially copied from a forum response from @mighty ledge
Any errors in logs?
I'm using this template to tell me how many lights are on in my HA. It shows 1 but when I go through all my lights in HA they all show off. Is there anyways to see which one its reading as on?
{{ states.light
|rejectattr('attributes.is_deconz_group', 'eq', true)
| rejectattr('attributes.entity_id', 'defined')
| selectattr('state', 'eq', 'on')
| list | count }}
All my lights are govee lights. Even when using the govee app the all show that they are off.
Not that I can see....
Remove the '|count'
When I remove that it breaks
he was saying remove the | count to see what one it is
Ah okay
Thanks now I realize. It’s a light that I no longer use and deleted from the Govee app but was still in my device list on HA. Last was on when used.
Deleted it and now shows zero
what does today and yesterday output?
52790.0 and
0.0
I created that last one (utility meter) today, so it wont have a positive value until tomorrow
seems to be something with that last row
you need |float on your today line
you are dividing by 0, that's not possble
what's the value of yesterday and today before eq
52810 and 0
So you are saying I cannot make the template until I have a value for the second sensor?
no, you need to guard for that
well you can build in safety with an availability template
as a sidebar, I would expect the equation to be...
(((today / now().hour) / (yesterday / 24)) * 100) | round
if you don't like the availability template because you want it to return something else, you can do something like this
{% set today = 52790.0 %}
{% set yesterday = 0 %}
{% if yesterday %}
{{ (((today / now().hour) / (yesterday / 24)) * 100) | round }}
{% else %}
Whatever you want
{% endif %}
Tried with another sensor and it works now. Your new equation gave almost the same result
it will solve itself anyway after today when you have data for yesterday
thank you
struggling to understand this though. This gives me a value of 229. But I was expecting something along the lines of 100, as in "your energy usage is 100% more than yesterday"
{% set today = 40.0 %}
{% set yesterday = 20.0 %}
{% if yesterday %}
{{ (((today / now().hour) / (yesterday / 24)) * 100) | round }}
{% else %}
Whatever you want
{% endif %}
What time is it where you are?
21:37
So today will be 40/21=1.9 per hour
Yesterday is 20/24=0.83 per hour
it's 229% of yesterdays amount
if you want just the percent over 100, then you'd want to subtract 100
but then you'd get negative numbers if you're low for the day
(today - yesterday)/yesterday
Ok I think I'm following. Makes sense that you cant compare current hour with yesterdays total
that would aslo work probably
and not be limited to hourly values
although it would just be (today/yesterday)*100
Hourly seems rather inaccurate anyway
it really depends on what you want
if I'm remembering the post, the guy wanted todays hour compared to yesterdays hour
At 21:55 you are still dividing by 21, when you already have almost 22 hours if data
he had a way to do that
Ah, this was the -1 in his own calculation
yeah
For me I have todays energy, and a utility meter for yesterday with a daily reset, Which I think is correct?
My plan anyway was to mimic this
I want to exclude all entities with the name “segment” in it. How would I do that?
when I call for all my lights to show I would like to exclude anything with the name segment
|rejectattr('name', 'search', 'segment') or |rejectattr('object_id', 'search', 'segment'), depending on whether you mean "name" or "entity_id"
{{ state.entity_id }}
{% endfor %}```
expand is faster
@inner mesa what is this | from the start
for loops are always slow
I just provided the part that does what was asked for
sorry though it was a new thing been off site for a while
Given this:
{{ state_attr('sensor.dishwasher', 'end') | as_datetime - now() }}
does anyone know how you display that or format the result?
in the "templates" debugging tab I get "1:29:59.352724", but if I try to use that as sensor state attributes, I get null
what do you mean by this?
but if I try to use that as sensor state attributes, I get null
how do you want to display or format it?
it's a timedelta object
but without more info on what formatting is wanted, there's nothing more to say
ideally HH:MM, but right now I'd settle for anything other than null
nice
it's not "null", you said it was "1:29:59.352724"
correct.
{{ state_attr('sensor.dishwasher', 'end') | as_datetime - now() }} renders "1:29:59.352724"
strftime look at that
the exact same thing pasted into the attribute value of a sensor yields null
you'll need to show your template sensor definition
@tired sandal I converted your message into a file since it's above 15 lines :+1:
i have a feeling I know what you're going to say
strftime works on datetime objects, and this is a timedelta object
I don't see why that would result in null for that attribute
unless it hasn't evaluated yet
beats me
the state attributes show:
cycle_percentage: 48
end: "2024-06-13T02:53:00+00:00"
time_remaining: null
icon: mid:dishwasher
friendly_name: Dishwasher
you have a few typos in there
mid:dishwasher should probably be mdi:dishwasher and I don't know what power_staes is, but at least you're consistent
oh, you're referencing the end attribute from that sensor
you should just use this.attributes.end
👍
TIL that's a thing!
- name: "Dishwasher"
icon: mdi:dishwasher
state: >-
{{ states('sensor.104050531161036114_bsh_common_setting_powerstate') }}
attributes:
cycle_percentage: >-
{% set progress = states('sensor.104050531161036114_bsh_common_option_programprogress') %}
{{ 100 if progress=='unavailable' else progress }}
end: >-
{{ states('sensor.104050531161036114_bsh_common_option_remainingprogramtime') }}
time_remaining: >-
{% set end = this.attributes.end %}
{{ end }}
so, I'm getting "" from that now 🤔
cycle_percentage: 62
end: "2024-06-13T02:50:39+00:00"
time_remaining: ""
icon: mdi:dishwasher
friendly_name: Dishwasher
You removed |as_datetime
I did. I did that for debugging
- name: "Dishwasher"
icon: mdi:dishwasher
state: >-
{{ states('sensor.104050531161036114_bsh_common_setting_powerstate') | lower }}
attributes:
cycle_percentage: >-
{% set progress = states('sensor.104050531161036114_bsh_common_option_programprogress') %}
{{ 100 if progress=='unavailable' else progress }}
end: >-
{{ states('sensor.104050531161036114_bsh_common_option_remainingprogramtime') | as_datetime | as_local }}
time_remaining: >-
{{ this.attributes.end - now() }}
that gives me
cycle_percentage: 77
end: "2024-06-12 22:50:39-04:00"
time_remaining: null
icon: mdi:dishwasher
friendly_name: Dishwasher
{{ this.attributes.end | as_datetime - now() }} also gives me null
@inner mesa are you SURE you can do this.attributes.foo? I can't seem to find mention of it in the docs and updating other template sensors to do that seems to break them
interesting - i tried to do the self referencing thing elsewhere and got "unavailable"
in fact, not only do I get "unavailable" but it breaks the whole sensor
- sensor:
- name: "Next Trash Holiday"
#state: "{{ state_attr('sensor.next_trash_holiday', 'data').date | default('1970-01-01') }}"
state: "{{ (this.attributes.data).date | default('1970-01-01') }}"
attributes:
data: >
{% set day = (utcnow().replace(hour=23, minute=59, second=59) - timedelta(days=1)).isoformat() %}
{{ state_attr('sensor.republic_trash_data', 'data')
| selectattr('LOB', 'eq', 'Residential')
| selectattr('date', 'ge', day)
| first
This is kind of a side-quest but I wanted to get this working first on something I know works - you can see where I commented out the old implementation and replaced it with this.attributes.data
You're probably getting a template loop because the state and attribute changes are causing a state change, which is causing the template to be reevaluated. The log will tell you that
you can add a trigger that limits on what state changes the template will reevaluate
this works fine every time I change input_number.test:
- trigger:
platform: state
entity_id: input_number.test
sensor:
- name: this_test
unique_id: "1069a725-2fb6-496c-a9d8-b471379197d1"
state: "foo"
attributes:
date: "{{ state_attr('alarm_control_panel.area_001', 'changed_by_time') }}"
remaining: "{{ '' if this.attributes.date is not defined else now() - this.attributes.date|as_datetime }}"
@formal ember I converted your message into a file since it's above 15 lines :+1:
Does this one here look like it will be accurate? changed best I could...
@formal ember I converted your message into a file since it's above 15 lines :+1:
Tariff is Peak: 2pm to 8pm weekdays, Shoulder: 7am to 2pm and 8pm to 10pm weekdays and 7am to 10pm weekends. Off peak: All other times.
yes that will work
there was a recent post on this if you are interested in shorter ways to accomplish the same thing
https://community.home-assistant.io/t/template-outputting-code-as-part-of-the-string/738378/9?u=mekaneck
@willow wing I converted your message into a file since it's above 15 lines :+1:
Because you are not using the response variable "daily"
@marsh cairn do you mean this lines? "{{ forecast['weather.landshut_DWD'].forecast[0].condition }}" -> forecast?
i tried daily instead of forecast too, does not work
@willow wing I converted your message into a file since it's above 15 lines :+1:
You are still using forecast[... in the state.
yeah, daily are not working too
I'm not sure, if the templates slugify themselves. I'd try to write dwd in small letters
okay i try it thanks
Or try the service call in the dev tools and look, if the structure of that response is as expected.
the service call is working
I'm talking about the structure of the response
It will also be unknown until it is triggered the next time. The next full hour.
It you want it immediately, you would need additional triggers.
I am adding the following triggers to my triggered templates.
With those the template triggers on each HA start and whenever the templates are reloaded.
I haven't run into issues with that yet, but if you do, you might have to remove that.
- platform: homeassistant
event: start
- platform: event
event_type: event_template_reloaded
aah thats cool thanks. - Works now
What the heck is going on here? I'm on the tz UTC+10 so why is there not a 10hr difference between local true and local false?
Hi guys, just got into the realm of HA things and have a question. i have a spare minir2 lying around and would like to use the sonoff miniR2 s1/s2 ports to detect whether the gate is open/close. My test setup as of now is that when i press the button connected to S1+S2, the switch will be detected as "on" and when i release the button it will switch state back to "off". is it possible to use these states to show "open" and "close" instead?
My miniR2 has been flashed with tasmota and i understand i can use Template Covers to do it, but i am not so sure how to proceed. Anyone able to help?
Where are you trying to get it to show as Open/Close?
Easiest way is probably to change the Device Class to Door (go into customise and change the "Show As" dropdown)
DST was active on 1st of January 1970
so your local timezone was on +11 then
Ah! Thanks Fez.
im currently looking at it from the overview tab. i was looking to see if i can reflect the status and change the icon accordingly to the state
Yeah try changing it to a door, that should do it
Failing that, you could make a conditional card
my head is doing backflips lol
hmmm so like this?
Looks good
hmmm ok thank you! I will try other stuff when i get there haha
just started using HA yesterday
You’re in UTC+10 right now, but what was the offset on Jan 1 (1970)?
Put the date into the timestamp formatting so you can see what is happening. The timestamp attribute for an input_datetime that contains only a time will just be the number of seconds from midnight until that time. So it’s more like a “timestamp delta” even though that concept doesn’t exist. But it’s not a true Unix timestamp, because it can’t be because there is no date associated with it. When you send it to timestamp_custom it will take it as a true Unix timestamp, meaning the number of seconds since 00:00 Jan 1 1970 UTC.
Yep. Fez already pointed that out.
Ah crap sorry
i'm using REST and this is a valid JSONPath, but home assistant is complaining about it:
- platform: rest
unique_id: 'artemis_bebop_scroll_lock'
name: 'Artemis Scroll Lock (Bebop)'
resource: http://192.168.86.71:9696/data-model
value_template: "{{ value_json..IsScrollLockEnabled }}"
i also tried {{ value_json['Keyboard'].IsScrollLockEnabled }} which is valid using the JSONpath tester, but again, HA won't accept it
"{{ value_json..IsScrollLockEnabled }}" There's a double period there. Typo?
no. that's a valid JSONpath expression
"give me all the values for that key"
*instances of that key
Oh yeah. But I don't think HA accepts that. I'm not completely sure tbh and I'm not seeing anything saying it's valid/invalid in the docs.
yeah i don't understand. it says to use the jsonpath expressions for the value template, but then anything advanced just fails due to syntax
my issues is i don't know if the [{...}, {Keyboard: {...}}, {...}] keyboard item is always going to be in the second slot
because using value_json.1.Keyboard works fine
as well as value_json[1]['Keyboard']
Perhaps using the json_attributes_path might help? Not 100% certain, tbh.
it does, but then it sets the values as sensor attributes, not state. argh.
i guess i will have to settle for that:
- platform: rest
unique_id: 'artemis_bebop_scroll_lock'
name: 'Artemis Scroll Lock (Bebop)'
resource: http://192.168.86.71:9696/data-model
value_template: "Keyboard"
json_attributes_path: "$.['Keyboard']"
json_attributes:
- IsScrollLockEnabled
- IsCapsLockEnabled
- IsNumLockEnabled
state will never change but i can make a template sensor off the attributes
hello. how can i get the current time in the format HH:MM as a string?
{{ now().strftime("%H:%M") }}
thanks @frail dagger - assistance appreciated. The only thing I can think is the restart nulled out my sensors and they aren't auto updating. I think I need to add something to my yaml to trigger that
Not sure that's the case. They are simple template sensors.
So, they only show up as unknown when you restart? But afterwards, they are fine?
no, they're now unknown, even after removing the weather code
Post the full yaml.
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
also as a side note, the raw editor is definitely adding ' ' ' ' all over the place
You mean the file editor in HA?
in the raw configuration editor
Huh, so yeah, it's not saving the template properly.
Any reason you are doing YAML over say a template sensor helper?
following a how to from the guy who made the original dashboard. I also generally prefer code level, it helps me understand more
hold on that may have just been a bad copy/paste
Ok.
it is, working in nano is never fun, let me open it in a real text editor
Yeah, I was going to suggest using the samba addon and then using a real editor.
no I'm running raspian with HA docker install
Oh, EVEN BETTER!
So, one thing I would suggest is to use what d_sellers suggested here #frontend-archived message
Oh wait...
Wait... damnit. I just noticed this.
I may as well share my dashboard too, one minute
You have 2 sensor sections.
see check this out...... the extra '''''
name: '{{ states(''''sensor.day_en'''') }}, {{ states(''''sensor.date_en'''') }}'
I didn't add the ' ' ' ', they are just popping up
It should be this:
sensor:
- platform: template
sensors:
day_en:
value_template: "{{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}"
date_en:
value_template: "{% set months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] %} {{ now().day | string + ' ' + months[now().month -1 ] }}"
- platform: openweathermap_all
api_key: XXXXXX
latitude: XXXXX
longitude: XXXXXX
. . . doh
So, the problem is that you have 2 sensor sections defined. The first one gets parsed and then the second one gets parsed and overwrites the first one.
I'm going to blame my 4 y/o's coughing next to me for that dumb mistake
What I would do is actually put that into a sensors.yaml file and then do sensors: !include sensors.yaml
seems reasonable - I'm going to reboot really quick and get ready to toss my new laptop out the window
giving me errors with my yaml check
What's the errors?
can I have multiple platforms in one sensor ?
Yup. As long as they are list items.
- platform: template
...
- platform: openweathermap_all
...
Did you move them into a sensors..yaml file and do the include?
Ah, ok.
In that case, it should be:
sensor:
- platform: template
...
- platform: openweathermap_all
...
not indentations from what I can tell, ok still investigating
This is a portion of mine, for instance: https://dpaste.org/yKvof
Damnit. Messed that up.
- platform: template
sensors:
day_en:
value_template: "{{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}"
date_en:
value_template: "{% set months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] %} {{ now().day | string + ' ' + months[now().month -1 ] }}"
There. That's better.
that doesn't have the openweather
- platform: template
sensors:
day_en:
value_template: "{{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}"
date_en:
value_template: "{% set months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] %} {{ now().day | string + ' ' + months[now().month -1 ] }}"
- platform: openweathermap_all
api_key: XXXXXX
latitude: XXXXX
longitude: XXXXXX
this is what I'm trying to customize for my own setup: https://community.home-assistant.io/t/mobile-first-dashboard-a-minimalist-and-user-friendly-ui-for-your-dashboard/535580
honestly never seen anything like it before and it's incredible
different error. Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/configuration.yaml", line 23, column 16
Ok. Post the yaml again.
So that line is the latitude line. Are those values correct?
yeah just confirmed by plugging them into Google Maps
Oh, reduce the spacing by four on api:, latitude: and longitude: they need to line up under platform.
🤞
it's weird that this works: state: '{{ now().strftime(''%H'') }}:{{ now().strftime(''%M'')}}'
What’s weird about it? Aside from the quotes.
the quotes
ok, making progress! now to figure out the last remaining issue with this. It's not detecting the weather state (temperature it is, state it is not)
ok - more strange things but trying to figure out. I appreciate the assistance
The quotes don’t work. If you put that into editor, it doesn’t work.
it's working though, like the output is right in my dashboard
empty dashboard on phone, on computer it shows up....
quotes fixed that
Odd. That should not be the case. The double single quotes are invalid. But, if it works, it works. 🤷♂️
Double single quotes in a function call? Thats never worked in the editor that I know of. Not doubting you, obvs, but when I tested it just now, it failed on the double single quotes.
{{ '''foo''' ~ '''bar''' }} -> foobar
Right. But in a function call, this fails: {{ now().strftime(''%H'') }}:{{ now().strftime(''%M'') }}
yeah
sorry I disappeared, family emergency. Back to this weather state
not sure exactly what you mean here - is this the whole template sensor now? i.e: nested under a trigger?
I gave you a complete example that I tested
right, but I'm trying to make sure that I understand the example before blindly pasting it into my HA install
I copied it straight out of my templates.yaml file that I use for the template: section
It's not solving your problem, but is an example of a self referential template sensor
is there any way to get a translated state from a trigger.from_state object?
The double single quotes are escaped single quotes
moving my question here,
How can I get the State object from an entity_id?
well, according to your question in #automations-archived you want the last_changed property
if you want that for a single entity you use states.sensor.foo.last_changed or states['sensor.foo'].last_changed
replace sensor.foo with the entity_id you want it for
if your entity is a group entity (eg a light group) you can use expand to expand it to the state objects of it's members (which will work down until it only has single entities, which can be useful if you nest groups)
hello, i just created a helper template wich does a calculation of some sensors. It's logging starts from the moment i created this sensor. Is it possible to recreate its logging with the template formulla i entered? the sensors i used in the formulla all have +10 days of data
no, that's not possible
no
just ask, this is the template channel