#templates-archived
1 messages · Page 27 of 1
Yes 🙂
if yes, there's only 1 way to get around the , being used as a list
you have to template the entire data: field
so that the resolver doesn't change it to a list
Ty for the tip 🙂 I had another approach in mind but will definitely take a deeper look into your code after a good night's sleep
Basically all voice commands will build up a room "to clean" queue in an input text. An automation will
- fetch input text,
- store first item
- update input text with slice 1:]
- start cleaning 1st room
- wait for trigger "vacuum returning to dock"
- repeat until input text is empty
This way rooms can be dynamically added to the queue without interrupting the vacuuming process. Maybe a bit dirty of a workaround but I think it will do its job
All of this because Speech to text don't work from Google Assistant >> Home assistant*🙄
Hi everyone,
I have a number of Riemann sum integrals in yaml that I would like to convert to helpers. But I don’t want to lose my statistics in my energy dashboard. Is there a way to convert to helpers keeping the same id?
OOPs, nevermind, I got rid of the quotes and now it is numeric... DUH....I wrote a temperature template but it wont work on a gauge card because the state is numeric. How can I get it to show the float value I am sending?: template:
- sensor:
- name: average_temperature
unique_id: 'AvgTemp'
unit_of_measurement: "F"
device_class: temperature
state: >
"{{ (((states.sensor.Bedroom_temperature.state) | float) + ((states.sensor.Bathroom_temperature.state) | float) + ((states.sensor.kitchen_temperature.state) | float) + ((states.sensor.livingroom_temperature.state) | float)) / 4 | float }}"
- name: average_temperature
remove the surrounding quotes
and your case is all over the place
entity_ids are all lowercase
and you should be using states() instead of states.xxx.yy.state
and you're converting 4 into a float
there's much weirdness 🙂
and you can do all of that with a helper in the UI now
if you wanted to
I have a mini split integration that's working great, but i just noticed it doesn't have the hvac_action attribute. hvac_modes is a list (off, heat_cool, cool, heat, fan_only, dry), so I'm wondering if there is a way to use a template to track which mode is currently in use. Is that possible? None of the tutorials I've found on youtube are getting me there.
Am I understanding correctly that the integration does not give you any feedback as to what the AC is actually doing? And you want to create something to "remember" the last state that you sent it? Or something else? Question is not quite clear.
That's what's weird. Right now I can see it is set to "heat", but there doesn't appear to be any way to see a history of each option within the hvac_modes (for instance, when it the mode is changed). Separately I have a Nest in my house and I can easily chart the state changes using hvac_action because it returns a string. I can't seem to do the same with hvac_modes, I believe because it returns a list.
Can you copy from the developer tools exactly what the integration provides you, including all attributes? Assuming it is a climate entity?
The attributes? yes hold on.
hvac_modes: off, heat_cool, cool, heat, fan_only, dry
min_temp: 62.5
max_temp: 86
target_temp_step: 0.5
fan_modes: auto, low, medium, high
preset_modes: none
swing_modes: off, both, vertical, horizontal
current_temperature: 52
temperature: 62.5
fan_mode: high
preset_mode: none
swing_mode: off
icon: mdi:air-conditioner
friendly_name: Mini Split
supported_features: 57
I believe the "state" of climate entity is the current mode. Mode "heat" means "this will heat when the temperature falls below the setpoint". Action "heating" means "this is actively pumping out heat at this moment".
And what is the state?
heat
Understand that hvac_action is different than mode. hvac_action is not "the current mode", it's something else.
I see.
I guess this mini split just does not report back the current action, or the integration is not doing it properly
You may be right.
I'm looking in Grafana at a table and the state.last is blank for the past several time increments, and as i scroll down i get to a "heat".
Ok but again: the state is the current mode. hvac_action is the current action. Without an hvac_action key, you will not know if it is heating or idle.
Hi, I need help with the sun and sometimes I get tired of it and there's nothing I can do.
I would like to set "true" from sunrise to 11pm.
I tried different ways and none of them work.
"{{ state_attr('sun.sun', 'elevation') > 1 and now().strftime('%T') < '22:59:59' }}"
Seriously, I was convinced it was the same 🤦♂️
So let's say something like this:
"{{ state_attr('sun.sun', 'elevation') > 1 and now() < today_at('23:00') }}"
Hi there. Can someone help me create a sensor to pull data from yesterday but only for a window of time. I have a sensor that measure my houeshold power consumption in kwh. I want to have a new sensor to provide predicted consumption for the next 2 hours based on the data from yesterday. Your help would be greatly appreciated!
templates can only access current data, not historic data
{{ (now().timestamp()-5260000) | timestamp_custom('%B %Y') }}
Is there a better way to get the previous month?
As each month is pretty much a different day, I get inconsistency at the end of each month
{{ now().month }}
This output the current month
But you could also subtract a timedelta of 1 month which would be better
Except that timedelta doesn't take months 🤔
What problem are you trying to solve? I wonder if there's a simpler way to do this
Thats my problem, february has 28 days, some months have 30
It will be inconsistent
Yes, except if we know the real problem, we can probably find a neater solution
I have an energy graph, it shows me 4 months of forecast, hence I need the label to state what month the forecast is displaying.
{{ now() }}
{{ now().month }}
{% set year = now().year %}
{% if now().month == 1 %}
{% set year = now().year - 1 %}
{% set month = 12 %}
{% else %}
{% set month = now().month - 1 %}
{% endif %}
{{ year ~ "-" ~ month ~ "-" ~ now().day }}
Someone smarter than me can definitely improve that, but that's a quick proof of concept for outputting a string.
You could modify the last line to turn it into a timestamp if needed.
{{ year ~ "-" ~ month ~ "-" ~ now().day | as_datetime }}
Of course, you may still end up with Feb 31st, but it sounds like you don't need days
I dont need days
Except, now its more complicated hahaha
{{ now().month }} is there a way that I can get this to show February instead of 2
Ah thanks!
Sunrise < - > 23:00
I want to use the new enum device_class to describe the states of my coffee maker, deriving them from a template based on power draw. Does anyone know the syntax?
syntax of what...
Another question for you: I have a sensor for my Fish Tank (in the glass), that shows some fluctuation when the Heater is ON or OFF.
But since it's OUT of the water, it has a variation of 2.5ºC below of what I want to actively show.
I thought "Ok, this is easy, I will create a helper input_number as ºC with 2 in the value, and create another sensor, with a sum sensor tank + 2ºC sensor. But it shows as unavailable?!
How can I achieve that "2.5ºC sensor" to SUM with the actual temperature of the Fish Tank sensor and make it display a proper value?
Since my go-to solution clearly failed hard lol
post what you tried
there's most likely an error in your syntax
I just created a helper adding a sensor and input_number and it worked
That's the fake helper I created, and then I did a regular "sum sensor" combining the fake and real one. But it shows as unavailable on the "final" sensor.
Is it the unit I'm using?
Both are meant to be in ºC
unit_of_measurement: ºC
taht is not a value
The value is 2.5, in the "Informações" tab
screenshot the full devtools attributes for the sensor and the input_number?
I would just make a template sensor 🙂
Will do, give me a second. I'll SS the 3 sensors.
I thought about the same Rob, but in this case, I also kinda wanna try and learn how to "fix it" so I know in the future :p
If possible, ofc
{{ states('sensor.fishtank')|float - 2.5 }}
hey all, I have about 30 binary sensors (binary_sensor.xxx) from my security system that has an attribute called "Tampered", with value of false or true. I'd like to create a trigger based on this this, that if any of these sensors gets tampered (i.e. true) to let me know. I'm not exactly sure how to listen to all the sensors with attribute and how to bring in the name of the sensor into the trigger ID so it becomes part of the message. I can do it for one specific sensor, but to do it all 30...not sure how? thanks for your help
the most straightforward way to do it is just to list them all in a state trigger
Here is the sensors: https://ibb.co/Mfq7wLQ
Oh this on the UI would fix it too, I think. Appreciate this.
Please can you check what I'm doing wrong on the sensors themselves so I understand where I'm "f-ing up".
you can't create a template sensor in the UI
got it, you mean create a group, right?
no, I mean list them all in a state trigger
Oh I thought you meant to use on the UI, with the state.
It still won't work on templates - just tested tho.
Fixed it, created a template sensor. I can't seem to make the measurement work with the helper. Thanks!
In the pull request for this there is some mysterious reference to “options” which are define for the enum device which then appear as a select in the UI for writing automations.
that's a select entity, which does not have device_classes
enum is on sensor only
so, this is why I'm asking
there is no syntax
for the enum device_class
You can make input selects or template selects
You may be able to set an options attribute on a sensor entity via customize.yaml or a template sensor that has a list of options combined with device_class enum. But there's no guarantee's that it will work.
Hi, I'm facing a weird issue where using a sensor's name in a template sensor makes the template sensor entity not work/show up in developer tools. Is this a known issue or I'm doing something wrong?
{%- for sensor in window_sensors -%}
{{ sensor.name + " - " + ("Open" if sensor.state == "on" else "Closed") }}
{%- endfor -%}
Using sensor.name like here makes the entity not work, but when I remove the reference to the name or substr it with [:3], the entity works.
because you probably are using strings and not state objects
what does windows_sensors contain a list of?
{% set window_sensors = states.binary_sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'window')
| list %}
no weird characters in the names itself either
I think there's no error at all - it works when testing in developer tools template, but when actually using in configuration.yaml sensor object in or in template object, the behavior is that it works when the name is not referenced
so that's really intriguing
not really, 9 times out of 10, it's your yaml that's bad in that case
@inner mesa looking to your automation here:
entity_id: input_number.zones_violated
value: >-
{% set orig_value = states('input_number.zones_violated')|int %}
{{ orig_value|bitwise_or(2**state_attr(trigger.entity_id, 'index')) }}
look like you made input helper, and your attribute is 'index'
just curious, what this bit does?
just ignore that, I was playing around
ok! sounds good
there's only 1 bug that's currently been found w/ differences between the template tester and templates inside configuration.yaml. And the bug only affects expand
so, post your entire yaml
and this part, will show the friendly name of the trigger.
message: "Zone: {{ trigger.to_state.name }} Violated"
@mighty ledge https://pastebin.com/CCVEwf4i here it is. removing sensor.name from L56 makes the entity work, otherwise it's not appearing anywhere
the strange thing is, the name reference in moisture sensors works just fine
one difference I can see is that one of the window sensor's has a hyphen in its name. let me check that..
that shouldn't matter
if it did, you'd see an error
in your logs or wherever
I don't see anything wrong with the template and it should work with what you have
it works until sensor.name[:8] , then (9+) the entity stops working. 8 is when a space appears in the window sensor's opening entity name
Okay there is an error actually lmao 😛
homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.home_status. State max length is 255 characters.
this might be it
So I'm trying to make a status message to send via IM periodically, and looks like it will exceed 255 characters. What's the best way to work around it? I could paste the template in the actions itself, but then I don't have a single source of truth for it and not really a good solution imo
One thing I can think of is making an automation which generates the string and writes to an input_string and then in the destination flows triggering that automation and reading that input_string
Alright, thanks a lot for helping me debug this 🙂
Make it an attribute of the sensor, not the main state
Oh. So I should probably do the same with other sensors. Thanks a lot!
{{ (today_at().replace(day=1) - timedelta(days=1)).strftime('%B')}}
I am getting a template error on a sensor that has worked for months. ```
TemplateError('TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'') while processing template 'Template("{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') *1000}}")' for attribute '_attr_native_value' in entity 'sensor.bill_gradient'
Runs fine in developers tools
sensors:
bill_gradient:
friendly_name: "bill_gradient"
unit_of_measurement: '%'
value_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') *1000}}"
The state_attr() function will return none when the attribute is not available, and you can't multiply none with 1000
Use a default or availability template to prevent the error
That would be a probable moment for this error to occur
sensors:
bill_gradient:
friendly_name: "bill_gradient"
unit_of_measurement: '%'
value_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') | default(0, true) * 1000 }}"
Or
sensors:
bill_gradient:
friendly_name: "bill_gradient"
unit_of_measurement: '%'
value_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') * 1000 }}"
availability_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') is not none }}"
Saw is_state_attr() in the template docs. Is this an option as well?
Nope
{{ is_state_attr('sensor.a', 'b', none) }} #False
{{ is_state_attr('sensor.a', 'b', None) }} #False
{{ state_attr('sensor.a', 'b') is none }} #True
Thanks as always for your quick response and fix for me
Can someone help me brainstorm this:
@grizzled grove I converted your message into a file since it's above 15 lines :+1:
And, now, at 1pm, instead of '0' it gives '1'.
So I tried adding:
{% if states('sensor.time') >= '08:00' %}
At the top. But it still doesn't give the else: 0
I think you're just doing string comparisons, which is unlikely to do what you want. What is this actually trying to achieve? The number of hours since 8am or something?
It's connecting to scrape sensors, that give net(solar) radiation by hour.
I'm just using numbers to simplify it.
you can't do direct comparison of strings like "08:59". You need to convert to datetimes or timestamps or something.
{% set h = states("sensor.time") | as_timestamp() | timestamp_custom("%H")|int %}
{% if(h < 8 || h > 17) %}
0
{% else %}
{{ h - 7 }}
{% endif %}
how about this
well, as long as you use 24-hour time and zero-fill, you can 🙂
Not much luck. =T
The strange thing is that it was working well during the day. Could it be related with the sensor.time going '00:00' and forward...
At '18:00' the value was '0'. As it should be.
Well, it seems that if I add:
{% if states('sensor.time') <= '08:00' %}
0
I'm able to constrain it after midnight.
Not the most elegant solution, but still...
I would do {% if now() < today_at('08:00') %}
No need for a sensor.time for templates
Is there a way to transform this equation: https://www.fao.org/3/x0490e/x0490e0i.gif
into a template?
I've been trying for a while now, without much luck....
when using selectattr filter, how can i exclude entities where the attribute is unavailable
or must i use if in the actual iteration of the result?
selectattr('attributes.your_attribute', 'defined')
it's the main state that is sometimes not defined though, not an attribute
for example,
{% for state in states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', '==', 'battery') %} {{ state.name }}={{state.state}} {% endfor %}
produces this:-
Aqara Roller Shade E1 battery=unavailable
Aqara Temperature 5ef3 battery=unavailable
Fire Battery Level=21
i'd like to filter out the unavaiulable
oh i phrased my question badly there, didn't i
selectattr('state', 'is_number') should work in this case
more general selectattr('state', 'ne', ['unavailable', 'unknown'])
HI,
every time my gate opens I make a notification on my phone. I would like to know how to make it show who opened on notification. (i know the name in log.) Someone can help me please ?
you need the context for that
service: notify.mobile_app_steven
data:
message: Action portail {{id_user}}
data:
color: green
I just want to know who pressed the dashboard button and put it where there is id_usser
I need some help on some template code. I'm pretty good at reading code and figuring out some of the changes that needs to be made but on this one I need some help on figuring out how to update a sensor which represents a file path.
As an example, I have a sensor
sensor.3d_printer_current_print with state = "subdirectory/filename.gcode"
but it could also be "filename.gcode" if the file hasn't been put into a subdirectory.
Each of these files produces a thumbnails but the api call always returns the thumbnails path relative to the filename and not relative to the main directory so whether the file is in at the main level or in a subdirectory the relative path of the thumbnails is always
3d_printer_object_thumbnails ".thumbs/filename.png"
What I would like to do is to modify the thumbnail relative with the subdirectory name available in the sensor.3d_printer_current_print if it exists.
is this possible.
I have no control on what the API returns when we do the call
You have to show your whole automation and describe how you're opening the gate. The context object contains the user data, but only in specific scenarios. without your scenario and your FULL current automation, we cannot help.
What is the expected path from your example that you posted here?
Dah... Sorry the final path of 3d_printer_object_thumbnails should be in this case "subdirectory/.thumbs/filename.png" if the original file is in a subdirectory and that subdirectory would be the same as the .gcode file is in , other wise leave it as is
I have an ESP32 with a relay that activates my gate. In the logs I can see who pressed the button on the dashbaord (thanks to the name of the phone it was selected with)
Then my automation is simple. I send a notification each time the button is pressed. I just want to add the name of the person who operated it. I don't know how to explain more...
@viral sierra I converted your message into a file since it's above 15 lines :+1:
{% set dir = states('sensor.3d_printer_current_print') %}
{% set img = states('sensor.3d_printer_object_thumbnails') %}
{{ [dir.split('/')[0], img] | join('/') }}
message: >
{% set user_id = context.user_id %}
{% set person = states.person | selectattr('attributes.user_id', 'eq', user_id) | map(attribute='entity_id') | first | default %}
{% if person %}
Action portail {{ state_attr(person, 'friendly_name') }}
{% else %}
Action portail unknown
{% endif %}
grr you beat me to it
slightly different approach
{% set user_id = context.user_id %}
{% set user = states.person|selectattr("attributes.user_id", "==", user_id)|map(attribute="attributes.friendly_name")|first if user_id else 'Home Assistant' %}
don't have to test anything
I had to search for Rob's post on the forum 😛
ah
It doesn't work ...
service: notify.mobile_app_steven
data:
message: >
{% set user_id = context.user_id %} {% set person = states.person |
selectattr('attributes.user_id', 'eq', user_id) | map(attribute='entity_id')
| first | default %} {% if person %}
Action portail {{ state_attr(person, 'friendly_name') }}
{% else %}
Action portail unknown
{% endif %}
data:
color: green
ah this was for your cursing Alexa, I kinda remember that
i have unknown when i pressed it
In the UI or physically?
UI of course ^^
Then it should work But you can't just call the service, you have to perform the automation
calling the service does not pass context
has to be the automation
maybe try with a state trigger?
trigger:
- platform: state
entity_id: switch.portail
to: "on"
i would like to show you the log ? Can i send somewhere ?
Also, you can't use the 'test' button for the automation, as that doesn't pass the context either.
well it does, just not the user
so, let the automation run naturally, or add a separate testing trigger, just to test it
if you go automation trace, and then press changed variables what does that show?
specifically the context part under this (not the context in the trigger part)
I'm 99% sure he's just testing it via the service caller or the test actions button
The only way it wouldn't work via the actual button in the UI, would be if he's using a custom card. But even then, it passes some context and it should have the user_id
i've this :
@viral sierra I converted your message into a file since it's above 15 lines :+1:
hmm, there is a user_id on the trigger, but not on the automation itself
yes i just saw it
I don't use device triggers, and tested it with a state trigger. I can then see the user_id in the context of the automation
just use the to_state then
where ?
{% set user_id = trigger.to_state.context.user_id %}
It seems you have an automation that actually triggers it, not the UI
service: notify.mobile_app_steven
data:
message: >
{% set user_id = trigger.to_state.context.user_id %} {% set person =
states.person | selectattr('attributes.user_id', 'eq', user_id) |
map(attribute='entity_id') | first | default %} {% if person %}
Action portail {{ state_attr(person, 'friendly_name') }}
{% else %}
Action portail unknown
{% endif %}
as parent_id shouldn't be populated unless it comes from a script or automation
yep
doesn't work ..
how are you triggering it
he shared this, seems he is using a device trigger
still shouldn't change the from/to state objects
no sure
the to_state had the user id, so I don't see a reason why the above wouldn't work if triggered correctly
That's why I keep asking how he's triggering it
yet he hasn't replied
Context is heavily based on what triggers it
too fast for me..^^
show_name: true
show_icon: true
type: button
tap_action:
action: toggle
entity: binary_sensor.ouverture_portail
Ok, so then it should be working with 1 of the 2 templates previously provided
or there will be an error in your logs
i don't have an error on my log .. and when i use this switch i'have '' action portail unknown "
Post the trace again then
@viral sierra I converted your message into a file since it's above 15 lines :+1:
or use this
alias: SMS Portail
description: ""
trigger:
- platform: device
type: turned_on
device_id: c21090ec6bd71c661d14
entity_id: switch.portail
domain: switch
variables:
context_user: "{{ context.user_id }}"
trigger_user: "{{ trigger.to_state.context.user_id }}"
person: >
{% set person = states.person | selectattr('attributes.user_id', 'eq', trigger_user) | map(attribute='name') | first | default %}
{{ person or 'unknown' }}
condition: []
action:
- service: notify.mobile_app_steven
data:
message: Action portail {{ person }}
data:
color: green
that's my user id : user_id: cae95d0942d04e8ebd2d665206bf6110
yes, that's not the problem
the problem is that your template is failing to grab the person because we aren't looking at the correct context.
using the automation I just posted, triggering the automatin, then posting the trace variables here will show me what's going wrong.
@viral sierra I converted your message into a file since it's above 15 lines :+1:
i have nothing anymore
did you trigger it?
is there errors in the logs
I know I sound like a broken record, but this is automation testing 101
if the automation doesn't work, find errors in your logs
then post them
I have no log in changed variables
my man, your home assistant logs
Stopped because of unknown reason "null" at 1 février 2023 à 16:55:58 (runtime: 0.00 seconds)
Template variable error: 'context' is undefined when rendering '{{ context.user_id }}'
Error rendering variables: UndefinedError: 'context' is undefined
ok, delete this line from variables
context_user: "{{ context.user_id }}"
then try to run it
i have : action portail unknown
Yes, please show me the trace...........
I'm about to hit my frustration limit and walk away
@viral sierra I converted your message into a file since it's above 15 lines :+1:
is your person not attached to your user?
you can only know what people select things, not users
I'm not sure I understand but yes I would say
can i send you a picture ?
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.
ok, that doesn't help
go to developer tools -> template page and put this into the template editor
{% for p in states.person | selectattr('attributes.user_id', 'defined') %}
{{ p.name }}: {{ p.attributes.user_id }}
{% endfor %}
If your name doesn't show up, then you didn't create yourself properly
However you are triggering it, it's not passing the correct context user_id
are you logged into Steven right now?
Do you have multiple steven users?
of course
Then it doesn't make sense how your user_id that's in the trace is not the user_id posted in your screenshot
and unfortuantely, I can't tell how you're actually triggering things
Click on Settings -> People -> Top of page, click users
Then click on each one and find the one that has an ID of cae95d0942d04e8ebd2d665206bf6110
Hello, how to add in my condition for time from my trigger:
- alias: "Hallway LED Light Effect Frontdoor"
trigger:
platform: state
entity_id: binary_sensor.front_door
#for: 00:00:02
action:
choose:
- conditions:
- condition: template
value_template: "{{trigger.to_state.state == 'on' HERE I want to add timer 10seconds}}"
sequence:
Is it possible?
just make 2 triggers, 1 with a for, 1 without
then your condition will be based on the trigger.id that you set on the trigger
i'm trying to get the device name from an entity state in a template. My device's original name was VA1453602560, and i have renamed it in the UI to be "Hall Radiator Actuator". My template expression:
device_attr(device_id(state.entity_id) ,'name')
is returning the original name, not the changed name. The documentation for device properties https://developers.home-assistant.io/docs/device_registry_index#device-properties implies that I should get the correct name here (and probably the original name in the default_name property.
I see the same. I recommend filing an issue
found in a forum thread theres a name_by_user attribute but it seems not documented elsewhere
those properties are in the developer docs, i can't find anything about device properties in the user docs / template docs
anyway that provokes my next question- that attribute may be set, or None, it appears. How can i make an expression that defaults to the name attribute when the name_by_user is none? must i do it with if / iif or is there a clever filter type approach?
best i can do is:
{{ device_attr(device_id(state.entity_id) ,'name_by_user') | iif(device_attr(device_id(state.entity_id) ,'name_by_user'),device_attr(device_id(state.entity_id) ,'name'))}}
but it doesn't seem nice evaluating the name_by_user property twice
I think that's typically what "name" should do
as with "name" and "friendly_name" for entities
you could stick device_attr(device_id(state.entity_id) ,'name_by_user') in a variable to make it shorter
ok. thank you.
Does someone know how to style / animate the **badge **of a custom Mushroom Template Card?
I would expect it to work with something like this:
style:
mushroom-badge-icon$: |
ha-icon {
--icon-animation: wobbling 0.1s ease-in-out infinite alternate;
}
@keyframes wobbling {
0% {
transform: rotate(-5deg);
}
100% {
transform: rotate(5deg);
}
}
probably the friendly people in #frontend-archived
Ah sorry, thanks
please make sure to post it as code
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
sensor:
# - platform: dnsip
# - platform: dsmr
# port: /dev/ttyUSB0
# dsmr_version: 5
- platform: template
sensors:
daily_power:
friendly_name: Daily Power
unit_of_measurement: kWh
If I understand correctly this the old way to create template sensors?
Can I just rewrite them in the new way and restart HA?
You have no template there 🙂
But yes, that's the legacy format and you can switch to the new format
Ah, sorry, I only posted the first few lines
why this template is returning false: {{is_state('sensor.stefan_iphone_ssid.state', 'ThePingInTheNorth')}} and this template returns correct ssid: {{states.sensor.stefan_iphone_ssid.state}}
I think remove .state from is_state?
thanks, thats it 🙂
This is probably easier than I'm making it in my head... I have an entity with an attribute that is an array of numbers (hourly energy prices). I can figure out how to store each hour into a separate entity using a for loop.
But what I want to do is rank them. So let's say 6am is the cheapest rate, I want [0] to be "6". Any tips on how to go about this?
One message removed from a suspended account.
please don't crosspost
One message removed from a suspended account.
How do I create a template that matches the start of a context ID for the event trigger? My two doorbells use different ids so catching the event and checking which ID it came from ids how I determine which ids sending the event. I cannot match the entire ID though because it’s only the first approximately eight characters if I remember correctly of the 20+ character string that stay the same for each doorbell, the other digits change to numbers and letters that vary.
id: 01GRAK5YSFF97Kxxxxxxxxxxxx
{{ '01GRAK5YSFF97K' in trigger.event.data.context.id }} or however you get to it
What should the template for a numeric sensor return when it is unavailable? I have a new error in 2023.2 from my SQL sensors (where I cannot set the availability property) that
Sensor sensor.climate_all_energy_l30d has device class None, state class None and unit kWh thus indicating it has a numeric value; however, it has the non-numeric value: unavailable (<class 'str'>);
This is generated by my attempt at catching the error in the value template of the SQL sensor
{% if states('sensor.climate_all_energy')|is_number and value|is_number %}
{{((states('sensor.climate_all_energy')|float - value|float)/30)|round(3)}}
{% else %}
unavailable
{% endif %}
Is this specifying at the start of the string or would it search the entire string for that? in regex terms I was looking for '^01GRAK5YSFF97K' in case some crazy random chance the middle or backend of the string contained the same pattern. With that in mind is there a regex match capability?
it should return a number. If you want it to remain unavailable w/o the error, return None instead.
or, make an availability template
{{ states('sensor.climate_all_energy')|is_number and value|is_number }}
if that's sql, it doesn't have availability so you have to return None
Yeah it’s sql. Thanks I’ll make them all none
I'd recommend checking for both context id's instead of assuming the first x characters will not appear in other context_ids
For automating the heating in the house better I would like to do the following:
When there is motion detected without a 5 minute pause between 2 detection points (so motion detected on 13:00 and 13:04 is within 5 minutes) turn heating on 19c
Will this only be possible with a template, if so what things should I use? And what should the trigger be in this case?
That will return true if that substring is anywhere within the string. Try it yourself in Dev Tools > Template.
Count how many times that motion was detected in the last 5min with this? https://www.home-assistant.io/integrations/history_stats/
Then in an #automations-archived, use a numeric state trigger to turn on the heat if the state of the history_stats sensor crosses 2.
That could work, thanks @rose scroll !
@mighty ledge and @rose scroll thanks for feedback. unfortunately and fortunately I found out that they aren’t actually unique in the beginning it’s just that they’re changing more slowly in the beginning similar to like a hexadecimal the right side is changing and the left is changing much more slowly. Fortunately, that made me go a little further and found that it looks like I can use a different event for the Amcrest doorbell press other than the one example on the integration web page. “AlarmLocal” triggers right before the button press example “CallNoAnswered” that their example showed. And that has the “camera: Front Doorbell” in it also so I don’t need the id anymore to try and identify the doorbell. Will try this after work today and see if it works.
Hello, I wanted to make a sensor for my light switch. I got told that I need to make a binary sensor. Since I am pretty new to home assistant I am not sure how to do this. The sensor should turn to on/1 if my switch is beeing hold (already existing event: long_pressed) and to 0 if the switch is beeing released (already existing event: long_pressed_released).
I tried to google it as well as to find something in the docs, but I could only find anything which doesn't helps me. I thought maybe somebody can help me.
is this for a remote like hue / ikea or a mains powered switch btw?
it is for the homeatic ip switch in combination with dimming
holding to dim or brighten
ok just making sure you didnt instead just need a blueprint to control the former
Sorry, I am new here. Can somebody help me? I have a xiaomi robot vacuum and it has a sensor whitch shows when I should change filter. Unfortunately the unit of measurement is in second. How can I convert it to hours?
So the problem I have is how do I make it work if I have is to call an event with its specific data.
When I listen to the event "homematic.keypress" and holt the button long it will give me this:
address: 00019F2991C492
device_type: HMIP-WRC2
interface_id: RaspberryMatic-HmIP-RF
value: true
device_id: b43efa02235fd76d3d123353150fd065
name: Wandtaster Schlafzimmer
type: press_long_release
subtype: 2```
You can have a template binary_sensor use a trigger which can listen for your events to set the state
Couple examples: https://www.home-assistant.io/integrations/template/#turning-an-event-into-a-trigger-based-binary-sensor and https://www.home-assistant.io/integrations/template/#state-based-binary-sensor---change-the-icon-when-a-state-changes
The event trigger itself can be specific to various event_data that you've got above https://www.home-assistant.io/docs/automation/trigger/#event-trigger
@formal pivot I converted your message into a file since it's above 15 lines :+1:
Thank you NSX, I gave my best and since I am new I think I messed it up a bit or understood the logic wrong.
My sensors.yaml fails.
event_type: "homematic.keypressed"
event_data:
address: 00019F29914C89
device_type: HMIP-WRC2
interface_id: RaspberryMatic-HmIP-RF
value: true
device_id: b43efa02235fd76d3d897353150fd065
name: Wandtaster Schlafzimmer
type: press_long_release
subtype: 2
binary_sensor:
- name: szdim
auto_off: 1
state: "off"```
May somebody can help me out with that 
It can be confounding at times, but with YAML, whitespace is critical, one wrong space and your whole script is messed up
and there are both too many and too few spaces in there 🙂
So basically it is right but some spaces are wrong? Since it says missing proberty "sensors". But I thought the binary_sensor line defines my sensor szdim so it is just a spacing problem?
@obtuse zephyr I converted your message into a file since it's above 15 lines :+1:
I got botted
Also... state should probably start as on 🙂
Or... auto_off shouldn't be there
I turned it to auto_on: 1
So as I understand this it listens with this trigger to the event and if the event fires it will turn the binary_sensor (which it also creates there with the name szdim) to off
I feel like you probably want 2 triggers, one for press and one for release? Where it's on after the press_long and then is off after the release event? Or is a time delay sufficient for turning it off
Currently, your trigger is just on the release event
yes i thought maybe the auto_on: 1 turns it back to on after a second. The automation should be at the end like: "decrease brightness until release event fires (so in this case until the sensor szdim turns to off)
Also I pastes the code to the configuration.yaml which is probably wrong
so can I change unit of measurement on a sensor?
can I change a variable of a binary sensor trough a trigger?
I mean the state sorry. I want to change with two different trigger the state of one entity.
@verbal moth I converted your message into a file since it's above 15 lines :+1:
Hi! I am trying to make my IR light "smarter" using PiIR, light template and appdaemon. For some reason the min_color_temp_kelvin and max_color_temp_kelvin are constantly getting lost whenever brightness/colortemp changes. How can I set these variables permanently?
@twilit narwhal I converted your message into a file since it's above 15 lines :+1:
My light template
Nevermind - sorted it out. Needed to set these variables under homeassistant - customize - light.relir
If you're referring to more precise control of how the state of a template binary sensor changes in response to other factors, you should look into trigger-based template sensors. https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-numbers-selects-and-sensors
How do I properlyset this img line {% set img = states('sensor.printer_3d_file_metadata.attributes["thumbnails"][2]["relative_path"]') %}
- name: 3d_printer_object_thumbnails
unique_id: "IP59b37837-b751-4d31-98c2-516a52edf833"
state: >
{% set dir = states('sensor.3d_printer_current_print') %}
{% set img = states('sensor.printer_3d_file_metadata.attributes["thumbnails"][2]["relative_path"]') %}
{{ [dir.split('/')[:-1], img] | join('/') }}
availability: >
{% set items = ['sensor.printer_3d_file_metadata'] %}
{{ expand(items)|rejectattr('state','in',['unknown','unavailable'])
|list|count == items|count }}
icon: mdi:image
attributes:
friendly_name: "Object Thumbnails"
Failed to restart Home Assistant
The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/packages/moonraker.yaml", line 331, column 8
line 331 is {% set dir = states('sensor.3d_printer_current_print') %}
Indent the lines under state: > by 2 spaces
Thank you
It's not totally working yet https://imgur.com/a/i7fFG5s
seems it puts a block before []/.thumbs/SpringNutxyz002-400x300.png
This code was supposed to remove the file name off dir ending (directory1/directory2/filename.gcode) then apply it to the resolution.png file start (directory1/directory2/resolution.png) but it's doing this when it doesn't have a directory to parse ie if the picture is in the root directory instead of subdirectories.
In your expression, you've got an array in the first element (from split)
Sounds like that's probably empty and the /.thumbs.... is from img
How would I tell it to ignore the dir split if no subdirectories exist.
If that's expected, you can try {{ (dir.split('/')[:-1] + [img]) | join('/') }}
Yes it expected that the user may or may not add a directory to their gcode upload 😄
no change same issue
you sure you reloaded your templates?
I saved the yaml then restarted home assistant.
Paste what you have now, and can you echo dir and img?
- name: 3d_printer_object_thumbnails
unique_id: "10.13.37.4859b37837-b751-4d31-98c2-516a52edf833"
state: >
{% set dir = states('sensor.3d_printer_current_print') %}
{% set img = states.sensor.printer_3d_file_metadata.attributes["thumbnails"][2]["relative_path"] %}
{{ (dir.split('/')[:-1], img) | join('/') }}
That's not what I suggested?
Oh I missed the [img]
Now there is a box at the start and around the img
oh forgot the +
and what's the YAML you have now
Working https://imgur.com/a/BjuZTIN Thank you will test adding subdirectories as well now.
https://imgur.com/a/9OmX93Z multi directories working still, thanks again.
hi, is there a filter to escape special char to the standard one ?
I have an input select with word using Upercase and è or ë char.
I'm using it to match entity name, i put a | lower to standardize the uppercase, but i would like to convert a è to a e to
How would I get to event_id with this output?
{'state': 'active noification', 'last_updated': datetime.datetime(2023, 2, 4, 16, 52, 59, 959377, tzinfo=datetime.timezone.utc), 'event_id': '1675529574.936298-0ln426', 'occupancy': 'off'}
I used this to get the output above
{{ state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2') }}
try adding |slugify
what you just edited out should have been fine
It wasn't
I edited it to avoid confusion lol
But it gave me an error there was no attribute
UndefinedError: 'str object' has no attribute 'event_id'
oh
add |from_json
worked thank you :)
Not sure if I did that right.
{{ state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2') ['event_id'] | from_json }}
you did not
JSONDecodeError: Input must be bytes, bytearray, memoryview, or str: line 1 column 1 (char 0)
I wasn't sure where to put it lol
{{ (state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2') |from_json)['event_id'] }}
JSONDecodeError: unexpected character: line 1 column 2 (char 1)
Do custom binary sensors have to stay in the configuration.yaml now? I've been working on a Bed Occupancy Sensor with load cells and have created the working binary sensors in the configuration.yaml but would like to move it to the sensors.yaml file I have but can't seem to make it work in there. I also created a binary_sensors.yaml but of course it doesn't work either. This is the working code in the configuration.yaml:
- binary_sensor:
- name: Person 1 in Bed
state: "{{ states('sensor.bed')|float >= 60 }}"
- name: Person 2 in Bed
state: "{{ states('sensor.bed')|float > 20
and (states('sensor.bed')|float < 60
or states('sensor.bed')|float >= 90 )}}"```
Would the format change because it is in the sensors.yaml? I've tried several different variations but haven't had any luck.
Also, I've found that if I keep it in the legacy format, shown below, it will work correctly in the binary_sensors.yaml.
sensors:
person_1_in_bed:
friendly_name: "Person 1 in Bed"
value_template: >
{{ states('sensor.bed')|float >= 60 }}
person_2_in_bed:
friendly_name: "Person 2 in Bed"
value_template: >
{{ states('sensor.bed')|float > 20
and (states('sensor.bed')|float < 60
or states('sensor.bed')|float >= 90 )}}```
Do you want the template sensor yaml? It was actually given to me by you a month ago I think lol.
You can put the first one in an included file if you want, but it doesn't belong under binary_sensor:
the point isn't which file it's in, but that it's under the right tag
As in, the template sensor attr or the jinja
{{ (state_attr(''sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status'',''outdoor_2'') |from_json)[''event_id''] }}
TemplateSyntaxError: expected token ',', got 'sensor'
Thank you but I am still having issues. What tag should it be under? I tried removing the tag.
You have two single quotes at either end of each string. Replace them with one single quote at either end.
I know it's a simple formatting issue but just can't get it right.
Yeah that results in a jsondecode error
I was trying to understand what rob was telling me to try
The JSON decode error is closer to where you want to be. As it stands, you have something that HA can't even parse.
It sees a quote, expects to see a string, then sees another quote (the end of said string), and expects a comma before the next argument. Thus, you have too many quotes.
It needs to be under the template: key, anything else won't work with your original YAML. In configuration you can have template: !include template.yaml and then put your sensor lists in that template.yaml file
Is it line 20?
That's the template sensor being referenced in the Jinja..
I have a feeling that non-serializable date is throwing things off
What should I do to it
Could as | as_timestamp ? Obviously less readable, but a number that you can convert back if needed
How would I convert it back?
Now
JSONDecodeError: Input must be bytes, bytearray, memoryview, or str: line 1 column 1 (char 0)
Wow, I don't know how I couldn't grasp that. It makes sense now, lol. Thank you for the help!
What's the value now
Thank you too
Much better
Result type: dict
{
"state": "active noification",
"last_updated": 1675529579.959377,
"event_id": "1675529574.936298-0ln426",
"occupancy": "on"
}
Got it now
{{ state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2')['event_id'] }}
How do I convert the time back?
as_datetime
Awesome.
So, essentially I could move all of my custom sensors out of the sensors.yaml and into the template.yaml and just use the one instead of having two? Currently most of my sensors are still in the legacy format but I did just convert one and move it to template.yaml and it seems to be working correctly.
If they are for the template platform
Then yes
You'll need to modify syntax to the new style accordingly
Understood, thanks again.
yep, you bet
One message removed from a suspended account.
I’m trying to write some conditional icon color logic based on the light vs dark mode. How do I get the current value (to know if it’s light vs dark mode)
Oh the HA site is down
I want to create a template that controls the volume of one of my DLNA media devices. How do I do that?
Oh there it is again ^^
Template number I guess
Is it possible to use a template which returns a list of entities in dashboards entities-card ( type: entities entities: {{template | list}} ) <- Documentation says: A list of entity IDs or entity objects or special row objects (see below).
I'm new to HA and yaml and want to calculate the cost of my electricity by multiplying the energy used by the tariff. Can any one provide an example template to do this?
I think templates is the way to do this, but I'm not sure where to start ...
If you add it to the energy dashboard, it will calculate that itself
I wanted to do this myself on my own dashboard
I have a couple of smart plugs, I also have an integration that gives me the electricity price. Should I create one template that does the multiplication (current draw + current price) and then another reimann sum and then a utility meter or is there a better way to do it? (I'd like the data outside the energy dashboard. For instance I have a plug for the extension cord for my server and computer + peripherals. Or in my living room I have one "smart outlet" in the wall and then one just to the tv. So I want to calculate what the router/tvbox/lights around thge tv takes
What are these things called when you put them on the end is there a list of all the things you can do there? |urlescape, |timestamp_custom, |etc…
Filters. See the links in the channel topic
Thank you.
So I've been setting my sensors to unavailable when they are not available. core 2023.2 does not like that. What should I be setting them to now?
You mean by explicitly giving them the state unavailable or by use of an availability filter?
Any idea why multiple_active_events wouldn't work? It doesn't become true when there's more than attribute state with active event/active notification https://dpaste.org/5LtJf
@silent vector What are the current attributes and their values of this sensor?
Check the dpaste. State possible values are 'inactive' 'active event' 'active notification'
I can't see the current values there
Just go to developer tools > states and copy the current values
Oh my
🤦♂️
That's why I have been having issues ..
Lol
Hm still false
https://dpaste.org/8Q59J
The attribute values themselves of what you're interested in is still an object, not just a string, that's the state property
Explicitly. I've added availability templates. That seems to have worked.
So use this this.attributes.state.values()?
No... attributes is a dict
You still need to gather the attributes that are important and then interrogate that state property
You need to add | map(attribute='state')
Before select right?
Also.... I don't actually know in what order things would be evaluated within that template. I wonder if there may be an instance when those states first update, that the this.attributes reads the previous values
Hmm, I'm on mobile now, not completely sure if that actually works
@silent vector | selectattr('state', 'defined') | map(attribute='state') before select
Just tried this actually and seems to update as one would expect
Thank you for checking
For context on what I was doing with this, i'm creating an automation for frigate notifications. 3 cameras with a similar view will share a notification to avoid 3 separate notifications. I prioritize which will have the best view (that's the idea at least).
is there a neater way to deal with clamping an input_number between 2 values other than:
service: input_number.set_value
data_template:
value: >-
{{ [[(states('input_number.ch_accumulator') | float(default=0.0) + state_attr('sensor.boiler_cs_wdc', 'absolute_offset') | float(default=0.0)) | round (2), 5] | min, -5] | max }}
because the input_number does have a min and max set but if an automation then tries to set a value beyond that range it just fails
I'd love to have a way to force the number to be clamped between min and max
How about {{ ([-5, (states('input_number.ch_accumulator') | float(default=0.0) + state_attr('sensor.boiler_cs_wdc', 'absolute_offset') | float(default=0.0)) | round(2), 5] | sort)[1] }}
certainly easier to read... please help me understand this though: this will always return the second item in the sorted list. So how does it sort?
Three values in the list [min, your_val, max], If your_val > max, then max becomes index 1
Same situation for min
yep, you bet
a very elegant solution too 🙂
Hi folks - can anyone provide me some updated recommendations with the best way to display "Last Motion Triggered" from a group of binary sensors? Open to implementation, I have a bunch of motion sensors around the ingress parts of my house and want to have a single sensor that shows the name of the "last triggered" sensor
something like this:
{{ expand('group.downstairs_lights')|sort(attribute='last_changed', reverse=true)|map(attribute='entity_id')|first }}
Do note this doesn't work right after a restart, and it could display the last sensor which turned off, which could be different than the last one turned on
indeed. could use a template sensor with a trigger for items in that group turning "on" like: #templates-archived message
so, I built some presence sensors for my couch.... I have an input boolean which is On if any sensor is activated, and off if all sensors are deactivated.
I want to create a template binary sensor that will reflect the input boolean, and show either mdi:sofa, or mdi:sofa-outline to indicate presence
where are you stuck?
sucessfully stated problem, soldered up connectors, and tested sensors...
you just want a template that outputs a different string based on the state of an input_boolean?
no, diffent icons and dif string
icons are just strings
it's the simplest possible template
{{ iif(is_state('input_boolean.whatever', 'on'), 'mdi:first_one', 'mdi_second_one') }}
thanks.. was WAAAY overthinking it.
yeah
I was wondering, does something in the state object can tell me if it's a group ?
When looking it it raw, it display a list under entity_id
entity_id=['light.plafonnier_bureau', 'light.nanoleaf_bureau', 'light.glow_ecran_bureau', 'light.decoration_lumineuse_pinkie_pie', 'light.lampe_a_lave_bleu_bureau']
But obviously getting the entity id of it only return it's own and not that list
so, this, RobC:
- binary_sensor:
- name: Couch
icon: >
{{ iif(is_state('input_boolean.Couch_presence','on'), 'mdi:sofa','mdi:sofa-outline')}}
state: >
{{ iif(is_state('input_boolean.Couch_presence','on'),'Seated','Empty')}}
it works!
attributes.entity_id have the value, i can use that
entity_id should be all lowercase, but it probably fixes it for you
hi, is there any way to compare 2 calendar entries in a template as a condition ?
| rejectattr('attributes.entity_id', 'defined') did it for me
I mean :
if the content of
platform: state
entity_id:
-
calendar.https_fr_airbnb_ca_calendar_ical_4469997_ics_s_e6256b885a96633ce257165cea4d909a
attribute: description
yesteday is different from the one of today
so I can assume the renter changed
hey, i got another template thing i cant get inside of my head
i want to print out a string that seperates the states and the unit of measurement of all entitys that are inside a list. i tried something like this, but i cant access the variable of the for loop
can somebody help me here?
oh wow
searching and trying for 1 hour and coming to a solution myself 5 min after asking
thats tech support for ya
If you have mine, I would like it too 😄
I want to display the last time an entity has changed in an easy to read format. I've found
{{ relative_time(states.switch.licht_bureau.last_changed) }} but that displays in English. Native language (Dutch) would be quite nice. Is there a way to accomplish this?
Also tried {{ (as_timestamp(now()) - as_timestamp(states.switch.licht_bureau.last_changed)) | timestamp_custom("%H", false) }} but that doesn't round up. so 3:55 hours ago is still displayed as 3 hours
well, you get what you pay for...
I find that the support around here is very good, when approached from the angle that this is volunteers, offering up their free time, and expertise
this support, you pay for with well asked questions.
{{ relative_time(states.switch.licht_bureau.last_changed) | replace('hour', 'uur') | replace('minute', 'minuut') | replace('day', 'dag') }}
The issue is that future events beyond the next event are not available in the state object of a calendar entity. There is an add-on (https://github.com/kdw2060/hassio-addons/tree/master/hass-addon-calendar) that extracts that data into a sensor.
is there a way to get the systems set units (metric or imperial) in a template so i can change a conversion factor depending on the units?
nvm, worked out i can get it from the temp state atributes
Perfect ! Thanks !
trying to create a template sensor with associated attributes... its saying this is wrong:
- sensor:
name: docker_code_server
unit_of_measurement: 'MB'
state: '{{ state_attr("sensor.docker_code_server_memory","friendly_name") }}'
state_class: measurement
attributes:
- dmemory: "{{ states('sensor.docker_code_server_memory') }}"
- dstate: "{{ states('sensor.docker_code_server_state') }}"
- dstatus: "{{ states('sensor.docker_code_server_status') }}"
sensor is a list, not a map and attributes are a map, not a list
- sensor:
- name: docker_code_server
unit_of_measurement: 'MB'
state: "{{ state_attr('sensor.docker_code_server_memory','friendly_name') }}"
state_class: measurement
attributes:
dmemory: "{{ states('sensor.docker_code_server_memory') }}"
dstate: "{{ states('sensor.docker_code_server_state') }}"
dstatus: "{{ states('sensor.docker_code_server_status') }}"
thanks. that looks like it will work.
define 'it's saying this is wrong"
outside vs inside quotes don't matter so both should work
unless you're using something else to 'check'
vs-code was indicating an error by marking it all with red underlines
when I made NSX's chasnge it cleared up
Yes, well the point being is that it's incorrect about ' "" ' being invalid
It wasn't complaining about that though, attributes in the initial was a list and sensor was a map.
I swapped it in my response because I like consistency 🙂
ah, completely missed that!
I have this template binary sensor - which worked. I dont think I have changed it, but it continually now says "Unavailable" in the dashboard.
- name: Free Electric state: "{{ states('sensor.octopus_energy_electricity_current_rate') | float < 0 }}"
what might be causing this?
what is the state of sensor.octopus_energy_electricity_current_rate?
my guess is that it's not a number, and you provided no default, so it's not rendering the template and you have an error in your log about it
its a numerical value
put the template in
-> Templates and debug from there
your indentation is also wrong above. state: should line up with name:
it does in the config, not sure why it doesnt above
- name: Free Electric state: "False"
thats the output I get on the :devtools -> Templates.
but the dashboard still shows Unavailable
and it's really a binary_sensor and not just a sensor?
yes, it only needs to tell me if the unit rate is below 0 or not
I'm not questioning the reasoning, but the execution
and your indentation still looks wrong, so...
no i get it - trying to make sure it all lines up - appreciate it
I just dont get how its gone from working fine - to unavailable.
I removed the integration that feeds it the data a few weeks back, but added it again, ive double checked the entityID
yes it copies across wrong for some reason
usually that means that it added a xxx_2 entity_id
let me go and search for a duplicate with a _2
developer tools > states : shows only a single entity called Free Electric and the same for the energy sensor it reads
I have an input_text.history which has the the latest states "fork,knife,spoon,...." Is it possible to test input_text.history has state knife within the last 60 minutes?
you can create a template sensor that tests for that, and then use the last_changed property of that entity
Unfortunately I do not understand how to realize this with my input_text entity.
Is it possible to template a - service: call? I'm attempting to call multiple entities with the same variables. I've attempted to pass a list of names to the service call with ```yaml
action:
- service: >
{{ expand( 'light.group_diningroom' ) | map(attribute='entity_id') | list
| regex_replace(find="/?\d+", replace='variable_brightness') |
regex_replace(find="light./?", replace='') }}```
but the automation says "Stopped because of unknown reason "null""
Yes, you can template a service
If the template is working, replace > with >- and make sure the template is indented. I can't tell from my phone
okay, I"ll try that
Still no go. It does appear my regex sucks, as it's replacing everything after the first underscore, instead of appending the string "_variable_brightness" to the end of each result. I'm still testing
How would I get a list of all binary_sensor entities that have a device_class of "door" without using a for loop?
{{ states.binary_sensor|selectattr('attributes.device_class', 'defined')|selectattr('attributes.device_class', 'eq', 'door')|map(attribute='entity_id')|list }}
Fantastic, thank you! I was so close 🙂 Is there an "in" clause for selectattr? Or would I need to somehow do an "or" if I also wanted to include say "window" device_class?
@elfin nymph I converted your message into a file since it's above 15 lines :+1:
nvm, i got that but i got a totally different problem... but first i got to sleep
Yes, just use 'in' and a list
Jinja is so handy! Thanks for your help.
When not available, my templated SQL sensors are reporting the following error:
Sensor sensor.lights_all_energy_l90d has device class None, state class None and unit kWh thus indicating it has a numeric value; however, it has the non-numeric value: None (<class 'str'>); Please update your configuration if your entity is manually configured, otherwise create a bug report at https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+sql%22
What am I supposed to output to the sensor so that it doesn't complain? Is there a None which is not treated as a string? The error is being generated by the following template in the SQL sensor:
{% if states('sensor.all_light_energy')|is_number and value|is_number %}
{{((states('sensor.all_light_energy')|float - value|float)/90)|round(3)}}
{% else %}
None
{% endif %}
0 maybe? Depends on how you are using the result of this sensor
Ok for this onereturning zero is ok, but I have others where I want it to just be unavailable or something like that.
But this seems to be a generic problem with 2023.2 -- the sql integration now generates a whole bunch of such errors in the logs when HA is starting up -- something isn't ready yet and I think these type of errors were suppressed before.
not sure here, but maybe you can return unavailable instead in of none
that's how I started. Then I get the complaint that unavailable is a string
or actually provide none instead of the string "None"
provide.. typ0
{% if states('sensor.all_light_energy')|is_number and value|is_number %}
{{((states('sensor.all_light_energy')|float - value|float)/90)|round(3)}}
{% else %}
{{ none }}
{% endif %}
aha interesting let me try
or simply remove the else
{% if states('sensor.all_light_energy')|is_number and value|is_number %}
{{((states('sensor.all_light_energy')|float - value|float)/90)|round(3)}}
{% endif %}
or: {{ ((states('sensor.all_light_energy')|float - value|float)/90)|round(3) if states('sensor.all_light_energy')|is_number and value|is_number }}
Alas, if I don't return anything it complains it has an empty string:
Sensor sensor.kitchen_microwave_energy_l90d has device class None, state class None and unit kWh thus indicating it has a numeric value; however, it has the non-numeric value: (<class 'str'>); Please update your configuration if your entity is manually configured, otherwise create a bug report at https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+sql%22
It seems to be the same erorr as before
Except it doesn't mention the state (as it is none now and not "None")
yes exactly -- it really needs a numerical value (because of the history, and correctly so), but if there is some unavailability it fails and nothing will satisfy it. For template sensors I set the availability key, but here I am not sure what to do otherwise.
Hi Guys I'm really new to this and have tried finding examples to learn but have not been able to find any written example for me to understand how to actualy pull this off.
I'm trying to use a counter helper value as a trigger.
As an Example
mdi:fan
{% else %}
mdi:power
{%endif %}```
If theres any resources that i should first read up with examples other than the documentation on Home Assistant I would very much appreciate it as well!
{% if states('counter.fan_speed_state') | float(0) > 0 %}
Or, in a one line template:
{{ 'mdi:fan' if states('counter.fan_speed_state') | float(0) > 0 else 'mdi:power' }}
Actually...any particular reason you are using a counter to record your fan's speed?
And that 🙂
its an RF Fan. I originally had an input boolean for the on/off state but was wondering if i could just use the counter count of 0 to indicate it as being turned off, and the other values to correspond to their speed values.
being new to this i wasn't really sure what other helper i should be using but when i saw counter, my monkey brain thought it made sense. is there perhaps a better way to do so?
From what I can gather, if i use int it should work too correct? float is just decimal points?
Check out input_select or input_number, aka Drop-down and Number in the Helpers menu.
Ah I did see that! I haven't actually tried it out yet but will do!
int will be fine as well
Thanks @rose scroll and @marble jackal for the guidance!
hi, is there any way to track if a thermostat value was changed either by a human on the thermostat himself vs by an automation ?
Yes, using a template condition that looks at the context object
do you have an exemple ?
examples most likely won't help as the context object differs for what you intend to use it for
you need to reverse engineer what context you care about
context.user_id
context.id
context.parent_id
no there isn't a better way
you have to find out which id matches a context objects id
users have ids, it's an attribute of a person. So if your person does not have a user attached, you won't get context
automations, scripts, scenes, etc have an id, it's context.id
and you have to figure out which id matches the context object in your current automation.
the object in your current automation will come from your trigger
e.g. trigger.to_state.context
thanks, I will try to figure out how to implement that
hello, i'm using this template sensor for calculating cost on current energy monitor:
https://nelim.han.bg/template.txt
But now i try to switch utility_meter with same policy in automation with this one:
https://nelim.han.bg/automation.txt
I'm definitely doing something wrong, can someone help?
With what? What is wrong?
hm.. i can create second sensor to switch peak/offpeak and use it as trigger maybe
it does not set variable tariff properly
why use a time pattern trigger
just use a time trigger on all relevant times
trigger:
- platform: time
at:
- "06:00"
- "07:00"
- "22:00"
- "23:00"
and your template has a double quote at the end which should not be there
yep, that will trigger only 4 times a day, not 24, with both hours for winter and summer
doh
i think the double quote is problem, let me try
you might want to add a home assisntant start event as trigger though, for when your HA is not available when it should trigger
yeah, cool, it is working 🙂 double quote was the problem, now i will optimise it with better triggers
thank you very much
tariff: >
{% set winter = [1, 2, 3, 11, 12] %}
{% set start = today_at("07:00") if now().month in winter else today_at("06:00") %}
{% set end = today_at("22:00") if now().month in winter else today_at("23:00") %}
{{ 'peak' if start < now() < end else 'offpeak'}}
@azure tinsel you could also use that for your template
lol.. looks much better
small copy paste error 🙂
@marble jackal yep, thank you very much, everything working now, and looks a lot better 🙂
@quasi widget do you know where the template tester is?
I know where templates under development tools is ^^
lg webos integration
Hi, i want to create a binary sensor from a sensor with attribute someone can help me
before we proceed ... in my mind I'd need a script that basically alternates between the screen on and screen off actions each time it's run
Ok, @quasi widget put this in your tempalte and paste the response here
{%- for e in expand(integration_entities('webostv')) %}
{{ e.entity_id }}:
{%- for key, value in e.attributes.items() %}
{{ key }} -> {{ value }}
{%- endfor %}
{%- endfor %}
Yeah, the only way you can do that is if you 'know the state'
or at least track something in the background
Right, can't know the state, so basically know what the previous action was and run the other
well, can you just put code I wrote into the template editor?
then paste the results here
yes, gimme a sec
media_player.lg_c2_webos_smart_tv:
source_list -> ['Apps', 'HDMI 2', 'HDMI 3', 'HDMI 4', 'Live TV', 'Media Player', 'PC', 'Web Browser']
volume_level -> 0.12
is_volume_muted -> False
source -> PC
sound_output -> tv_external_speaker
assumed_state -> True
device_class -> tv
friendly_name -> LG C2 42"
supported_features -> MediaPlayerEntityFeature.PLAY|STOP|SELECT_SOURCE|VOLUME_STEP|PLAY_MEDIA|TURN_OFF|NEXT_TRACK|PREVIOUS_TRACK|VOLUME_MUTE|VOLUME_SET|PAUSE
ok
so, only 1 entity
and it's already assuming the state of the TV it looks like
so, make an input_boolean, name it lg_screen or something
ah yes, I thought we might come to input_boolean
you're assuming I know how to do that, haha 🙂
then, make a template switch (place this into configuration.yaml)
switch:
- platform: template
switches:
lg_screen:
name: LG TV Screen
value_template: "{{ states('input_boolean.lg_screen') }}"
turn_on:
- service: homeassistant.turn_on
target:
entity_id: input_boolean.lg_screen
- service: script.turn_on_lg_screen_script
turn_off:
- service: homeassistant.turn_off
target:
entity_id: input_boolean.lg_screen
- service: script.turn_off_lg_screen_script
input_boolean:
lg_screen:
name: Turn TV screen on and off
icon: mdi:whatever
would making an input_boolean look something like this?
what kind of helper do I choose, toggle, switch as x ... ?
(sorry about these basic questions, but I've only a very vague grasp on things, haha)
toggle
yep, did that
alright, I put the above code in configuration.yaml, put in the right script names
in the name: line it say Property name is not allowed
it's probably friendly_name: instead of name:
here
I did that, yes, put in the names of my own screen on and off scripts
Screen On / Off Toggle Switch
switch:
- platform: template
switches:
lg_screen:
friendly_name: LG C2 Screen On / Off
value_template: "{{ states('input_boolean.lg_screen') }}"
turn_on:
- service: homeassistant.turn_on
target:
entity_id: input_boolean.lg_screen
- service: script.tv_screen_on
turn_off:
- service: homeassistant.turn_off
target:
entity_id: input_boolean.lg_screen
- service: script.tv_screen_off
Ah, indeed, got it.
if you want to manage that from the UI, add unique_id: lg_tv_switch between friendly_name and value_template
at the same indendation
then you'll have a switch you can manage in the UI, i.e. you can put it in an area
damn, it works!
just keep in mind that it will get out of sync when you change it via the remote
but if you use switch.toggle as a service, it won't matter
well, the point of this whole thing is to never use the remote 😛
I'm using my C2 as a monitor
yes
I only use my remote now to fix things
other than that, my wife and I use HA in our phones
nice
that's a project for another day, for now I'd like to make a macro pad that controls my C2, mostly screen on/and off and power on/off
since I have your attention, as I understand it the most practical way to go about it is via mqtt, right?
macropad sends hotkey to pc -> an mqtt enabled app catches it -> forwards it to HA -> runs appropriate script
can your macropad write directly to an MQTT topic?
if yes, then that's what I would do
otherwise your other option is to use webhooks if it can do webhooks
that would be the direct way, yeah, but no, it's a dumb wireless USB pad
if your macropad can do webhooks, then all you'd need is
macropad sends hokey to ha
you can even create webhook events
then an automation that runs a script based on the event
you have plenty of options
webhooks aren't easy but TBH, you didn't screw up the configuration.yaml portion that I posted, so you seem like you can do difficultt hings with directions
which oddly enough, following directions is a skill many people don't have.
right, but since the only thing this macropad can do is send HID inputs to the PC, I was thinking of using an application called HASS.Agent
thanks, I guess, hehe
I'm still in high water with all this stuff, but I'll get there
I use hass.agent
it's simple
I use it w/ mqtt too
because I was too lazy to set up the webhook stuff
if you already have MQTT broker on your network, it's always a goto for use IMO
if you don't, then invest in webhooks
either way, the option for both is yours
I did set up Mosquitto in anticipation, definitely plan to play around with mqtt
well petro, I'm gonna stop bothering you for now, you've been extremely kind and patient, thank you very much
np
I'm sure I'll be back at some point, heh, hopefully with higher level stuff 😛
have a good one
You too
Jumping over here from #automations-archived ... I'm trying to create a simple template for a message to publish over MQTT. But even my small test won't work out. Can't figure out what I'm doing wrong. Whatever I fill into "Payload template" comes back to "[object Object]": null once I save the automation.
that means you're outputting an object instead of a value that's json
json accepts: string, boolean, integer, double, null, list, or dictionary.
anything outside those types won't appear correctly
Hmm but shouldn't this return a string: {{ states('device_tracker.myphone') }}
It does in the template tester
it should, but you're doing that in Node red right?
No, this is in Automations
ok, post the full service you're using in yaml
I'm using visual editor, but this is what it creates:
service: mqtt.publish
data:
qos: "1"
retain: false
topic: /test/topic
payload_template:
{{ states('device_tracker.myphone') }}
you're missing >
if you plan to use multiple lines for your template, you need to use the multi-line yaml notation
Yeah I wasn't planning to, I wanted to do it in the Visual Editor
payload_template: >
Now it works if I manually create it in yaml
Damn, so the visual editor was the problem, now it works fine.
Thanks!
np
Guys I've made this automation but the remaining time on my timer is not updating, is there a way to calculate this based on "finishes_at" and give a response in "x hours" and "y minutes"?
{% set remaining = state_attr('timer.a_timer','finishes_at') | as_datetime - now() %}
{{ remaining.seconds // 3600 }} hours and {{ (remaining.seconds // 60) % 60 }} minutes
Got it working thanks! All good! 😄
Thanks!! now I can see the correct remaining time but for some reason Alexa still saying the "remaining" attribute variable
as in it's speaking the template instead of substituting the values?
Share what you have now
I don't completely understand what you're saying it's doing.... however, did you reload the automations if you're doing this outside of the UI ?
@faint marsh I converted your message into a file since it's above 15 lines :+1:
hi, I have a waste_collection sensor with the following attributes:
`types: Papier, Problemabfall, Gelber Sack, Restmüll
upcoming:
- date: '2023-02-09'
icon: mdi:trash-can
picture: null
type: Restmüll - date: '2023-02-13'
icon: mdi:recycle
picture: null
type: Gelber Sack`
How can I access the icon in the upcoming events array to use it in a template-card?
state_attr('sensor.your_waste_sensor', 'upcoming')[0].icon
that results in: UndefinedError: None has no element 0
At least in the template editor
Does that make a difference?
did you replace the sensor in my template with yours?
yes
{{ state_attr('sensor.your_waste_sensor', 'upcoming') }} this should return the array
Now it is working! I had to reset the Template Editor to Demo Template
Thank you very much
Hey there! 🙂 After searching for a little while I came empty handed. Maybe my search was not accurate for what I’m looking to accomplish. I have a Valetudo based vacuum and I want to create an entity that would allow me to see and change the current fan speed of the robot. Basically, the dropping list that let you choose the fan speed when you open the vacuum entity but as it’s own entity to integrate it into a dashboard. Is this possible? Thank you for your help.
Sounds like a select component. Open up the details for the entity, you can verify there
If I look at the entity I get : fan_speed_list:
- low
- medium
- high
- max
battery_level: 100
battery_icon: mdi:battery-charging-100
fan_speed: high
icon: mdi:robot-vacuum-variant
friendly_name: Dreame W10 appartement
supported_features: 8956
The vacuum entity seems to wrap it as a selector indeed. Thing is, I’m not sure how to only access the selector.
Not sure, in Settings > Devices > Entities tab, search for 'select', see if your vacuum is listed
Hi, I am a little confused as this template shows as "Unknown" instead of "off" when the upload/download sensors are "unavailable":
- name: "NAS Data Transfer"
icon: mdi:swap-horizontal
availability: "{{ not is_state('binary_sensor.nas_status', 'unavailable') }}"
state: "{{ states('sensor.nas_throughput_upload')|float > 50 or states('sensor.nas_throughput_download')|float > 50 }}"```
I am confused because I have another template that shows as 'off' when the volume status sensors are unavailable:
- name: "NAS Status"
icon: phu:nas-v2
state: "{{ is_state('sensor.volume_1_status', 'normal') or is_state('sensor.volume_2_status', 'normal') }}"```
how can I get my first template to show as "off" instead of "unknown"?
is binary_sensor.nas_status unavailable at that time? You'll want to add a default to your |float a la |float(0) otherwise you'll get a failed template execution (which is what unknown is telling you)
Right... so your Data Transfer sensor is still available
but if your upload/download sensors are unavailable
they can't be parsed to a float
So that'll blow up
So if unavailable == 0, then just add a default and you'll be good
sorry I am not sure what you mean by that - how do I add a default?
"{{ states('sensor.nas_throughput_upload')|float(0) > 50 or states('sensor.nas_throughput_download')|float(0) > 50 }}"
oh perfect! Thank you 🙂
Yep, you're welcome
It is not. 😦
From what I've seen on the Valetudo integration, you're probably using MQTT for this vacuum. I don't know anything about MQTT, but there should be a way
I’ll look into that but the robot format the MQTT topics to be represented as a vacuum so there’s no fan entity by itself. 😦
Yay I succeded with MQTT select entity.
Created an entity specifically on the FanSpeedControl.. topic.
hi I was creating an automation for morning call. It seems to end up in an error
Good Morning. {{ [ "I just provided a morning briefing including weather, and traffic conditions, and other things that ensure the residents of Anchorage House know what to expect today.", "Time for the daily update. It was like that scene in Ironman where JARVIS gives the daily briefing but no one was listening. ", "I have prepared a safety briefing to present to my residents but they would just ignore it.", "Do you like to be prepared for the day? So do my residents. So I provided them with an update on whats happening today.", "Sometimes I just like to be snarky, but this morning I decided to just tell everyone what is going on in the world.", "Homeassistant gives me the ability to make daily announcements like the one I just did using #Amazon Polly.", "Each day at this time I provide the residents of this house an update that includes everything they need to know about the upcoming day. But with more snark." ] | random }} {{ [ "The temperature today seems to be", "It seems like the temperature outside is", "The temperature <break time="1s"/>" ] | random }} {{ state_attr("weather.forecast_home","temperature")}}°Celsius, it is {{states("weather.forecast_home")}} outside. The date today is {{states("input_datetime.only_date")}}.
the error:
Message malformed: template value should be a string for dictionary value @ data['action'][1]['data']
I have a template like this: {{ states('sensor.caller_id') in ['1111111111', '2222222222', '3333333333'] }} which matches sensor.caller_id to that list. The problem is the state is not just a number, rather its also a name and the name contains a' so it makes it difficult. basically like this: John Doe' 123456789 how can I make a partial match to a list?
call its attribute?
{{ state_attr("sensor.caller_id'","some_attribute") in ['1111111111', '2222222222', '3333333333'] }}
the information I need is in the state. There is not any useful (for this) data in the atribute.
Hello.. can I make a (sensor) template that uses another sensor template?
{{ ['1111111111', '2222222222', '3333333333'] | select('in', states('sensor.caller_id')) | list | count > 0 }}
It'd help if you've got the full YAML and not just a snip, but this section has nested quotes that will be angry "The temperature <break time="1s"/>", can do "The temperature <break time='1s'/>"
Sure can
I created a template sensor that gives me the daily total cost of my energy.
- name: "Total daily Energy Cost" state: "{{ ((float(states.sensor.octopus_energy_electricity_17p2225658_1200025442284_current_rate.state) * float(states.sensor.octopus_energy_electricity_17p2225658_1200025442284_previous_accumulative_consumption.state)) + (float(states.sensor.octopus_energy_electricity_17p2225658_1200025442284_current_standing_charge.state))) | round(2) }}" unit_of_measurement: "GBP" icon: mdi:currency-gbp unique_id: "sensor.total_energy_daily_cost" device_class: monetary state_class: total
I use also a hacs integration (octopus) which provides a sensor with my total consumption in kWh for electricity and m3 for gas in 1 hour intervals.
Can someone help me understand how I need to set up my energy dashboard to track cost using this sensor?
My energy dashboard shows energy consumption just fine, but I’m struggling to link my daily cost to the dashboard.
You don't need to calculate the daily cost yourself. Just provide (a entity for) the price in the settings for the dashboard
Thanks for your help. I’m not quite sure I understand what you mean. Can you put me a quick example please?
In Settings > Dashboards > Energy you can provide a price for your energy. The dashboard will then calculate the costs for you
Yes I know but the price entity does not include a daily standing fee that I need to pay on top of my consumption. So with this sensor I was calculating my total daily cost (consumption + standing fee).
Is there a way to use my sensor to track cost in the energy dashboard or what I am trying is not possible?
No, that's not possible
Thanks! Can I ask why not? I’d like to understand limitations here so I can take them into account in the future.
I thought that “Use an entity tracking the total costs” option expects a daily cost value in your currency. What data I would need to provide with this option otherwise?
Or if you can point me to any documentation where I can learn more about how to configure energy dashboard, that would help too. Thanks
Is there a way to repeat until a 4 minute timeout? I tried 'repeat.index == 24' but it didnt work:
until:
- condition: template
value_template: "{{ is_state('binary_sensor.nas_status', 'on') or repeat.index == 24 }}"
sequence:
- service: homeassistant.update_entity
data: {}
target:
entity_id:
- sensor.volume_1_status
- wait_template: "{{ is_state('binary_sensor.nas_status', 'on') }}"
continue_on_timeout: true
timeout: "00:00:10"```
Because the costs on the dashboard are kWh * price. A daily fixed cost should be first divided by usage of that day, and then added to the price per kWh, but you'll only know that afterwards
Does anyone have a link to documentation on how to use templates in a dashboard card? I am using apexcharts and for one of the properties want to use an entity but the normal templating syntax doesn't seem to work.
I don't see why this wouldn't work
That's something for #frontend-archived
Thanks!
I'm learning the very basics of templating and I have a syntax question. How do I give an automation one action for each light in a group? I don't want a single action that operates on the group itself, but a distinct action for each group member. I don't understand where to put the {% for light in stuff, and I'm having trouble finding this online
Maybe you don’t need a template specific and can do it in such a way
https://community.home-assistant.io/t/for-each-attribute-action-in-automation/421918
That's what I would do
And speaking of templates, I’ve ran in an issue with an automation which is leading me to templates: I’ve got an Mqtt select that gets filled with the friendly names of my hue scenes (waf) so the spouse can select which scenes should run at a specific time of day. However I noticed (she complained;)) that some scenes didn’t work. So I noticed that for some scenes the friendly name and the entity Id didn’t match. Since I do a recall scene with a template that combines the friendly name with the room this triggers the error. So I’m in the templates test environment trying to figure out how I can get the entityid based on the friendly name. I’ve got a template that will select the correct one but I can’t get the entity I’d from it
{{ states.scene | selectattr('attributes.friendly_name', 'match','Living Room ' + states.select.evening_scene.state)|list}}
I tried with map(attribute='state') but I only got an date back not the entityid
I thought I was being clever by making a template to map a component's config values to dynamic inputs, like this: disable_brightness_adjust: {{ is_state('input_boolean.brightness_light_control_enabled', 'off') }}
(accepts true or false)
except that doesn't work?
Error loading /config/configuration.yaml: while parsing a flow mapping in "/config/configuration.yaml", line 243, column 33 expected ',' or '}', but got '<scalar>' in "/config/configuration.yaml", line 243, column 99
Does that mean I can't just use templates for values that don't accept templates? Is there a way to do this? I just wanted to not have to restart HA every single time I want to change these values
create a sensor to monitor the value for disable_brightness_adjust: and use that
I see, I know how to do that, can I just pass sensors to config values?
like those that accepts booleans or integers
try it and see 😉
I'll try
You need to place quotes around your template
I see, that indeed seemed to be accepted for the boolean but not for the ints
Not sure what you are referring to now
That's because you are requesting the state, which is a date for a scene. Try map(attribute='entity_id')
Tried this template sensor now:
adaptive_light_min_brigthness: friendly_name: "Adaptive light Min Brightness" unique_id: "AdaptiveLightMinBrightness" value_template: > {{ states('input_number.circadian_light_minimum_brightness') | int }}
and min_brightness: AdaptiveLightMinBrightness
but still:
Invalid config for [adaptive_lighting]: expected int for dictionary value @ data['adaptive_lighting'][0]['min_brightness']. Got None. (See /config/configuration.yaml, line 244).
so I'm trying to figure if it's the integration that just doesn't like using values from templates or if I don't know the syntax, that config value isn't a template value but I don't know if I'm trying to do something that can be done
You need to refer to the entity_id of your template sensor
oh right I forgot the "sensor." part
{{ states('sensor.adaptive_light_min_brigthness') | int }}
But you can also refer to the input number
The sensor is of no added use here
just tried doing min_brightness: {{ states('input_number.circadian_light_minimum_brightness') | int }} but it's still complaining about Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('input_number.circadian_light_minimum_brightness') | int", None)])" in "/config/configuration.yaml", line 245, column 0
Again the quotes around the template
right I forgot
Invalid config for [adaptive_lighting]: expected int for dictionary value @ data['adaptive_lighting'][0]['min_brightness']. Got None. (See /config/configuration.yaml, line 244).
Okay, then it doesn't accept templates there
yeah, so does that mean it just can't be configured through templates at all? no workarounds?
Maybe I am abusing jinja2 a bit, but I get a string of comma-separated temperatures from scrape, eg:
'-1 °C,0 °C,0 °C'
I would like to write a template to return this as a list with the units stripped:
['-1','0','0']
I can do a .split(',') to get a list and then a for loop to split each one and pick the leading part, but how do I get this back into a single list to then process later? Or mayeb there is a smarter way to do this using map?
('-1 °C,0 °C,0 °C' | replace(' °C', '')). split(',')
Thanks. This is smart!
I've been getting lost for some time now. I have a string value of time as %H:%M (unit_of_measurement: h; device_class: duration) that I want to add to the current time. Whatever I try, I keep getting error's that I can not do this. I have tried a couple of things with as_timestamp, which according to the docs should work, but that gives me the following error: ValueError: Template error: as_timestamp got invalid input '0.75' when rendering
How can I do this?
The value reports itself as H.M but due to duration it shows up in lovelace as HH:MM.
Same for strptime btw
Got it. timedelta with the state set to float.
Well, almost. It gives me the time in 6 decimals of milliseconds. How can I just have it show %H:%M? I now have this:
Sounds like you're looking for strptime: https://www.home-assistant.io/docs/configuration/templating#time
Another inappropriate jinja use -- I have a list of times of the format 17:00 over the next 24 hours. I would like to convert it to a list of isoformat dates, assuming that they are today if before midnight, or tomorrow if after. Because of the change of date I don't think I can use the today_at filter. I can easily do an if statement to figure out the correct date, but I don't know how to map this onto the list. I wanted to use a namespace and append to a list, but this returns unsafe. So I use a string namespace variable, append the times to a string and then split that. Is that the best way?
{% set times = [14,15,16,0]%}
{% set ns = namespace(datestring='') -%}
{% for time in times-%}
{% set bla = (today_at(time~':00').isoformat() if time|int>hour else (today_at(time~':00') + timedelta(days=1)).isoformat()) -%}
{% set ns.datestring = ns.datestring+bla-%}
{%if not loop.last-%}
{%set ns.datestring = ns.datestring+','-%}
{%endif-%}
{%endfor-%}
{{ns.datestring.split(',')|list}}
You can't use append, but if you kept it an array, you can add two arrays together to have the same effect. ex. [1,2,3] + [4] = [1,2,3,4]
{% set times = [14,15,16,0] %}
{% set ns = namespace(datelist=[]) %}
{% for time in times %}
{% set t = today_at(time~':00') %}
{% set t = t + timedelta(days=1) if t < now() else t %}
{% set ns.datelist = ns.datelist + [t.isoformat()] %}
{% endfor %}
{{ ns.datelist | sort }}
@analog mulch 
aha makes sense. Thanks
I want to hardcode the effect list for template light, but cant get my light effect list template to work properly:
effect_list_template: "{{ ['random'] | list }}"
What am I missing?
btw, is the final sort, because the order may not be preserved in the loop?
well, as 14 and 0 resulted in future datetimes it bade sense to sort it
well all are future, but those are the next day
ok, got worried that loops migth be non-deterministic or somethign
it was just to have them in a logical order
otherwise it would be 14:00 tomorrow, 15:00 today, 16:00 today, 00:00 tomorrow
['random'] is already a list (a list with one item though)
not sure what you are trying to achieve here
I want to define a "list" of effects for my IR lights. They have only one effect and that's a random loop. As far as I understand, to define supported effects I set effect_list_template, but no matter what I try nothing works :(
I get this when I try to load config: Invalid config for [light.template]: some but not all values in the same group of inclusion 'effect' @ data['lights']['relir'][<effect>]. Got None. (See ?, line ?).
I have no clue to which integration you are referring now
oh, a template light
what is your complete config for this template light
@twilit narwhal I converted your message into a file since it's above 15 lines :+1:
I control it through appdaemon script that issues commands to MQTT IR blaster
BTW you should make your unique_id's more unique.. bedroomlight is something you might reuse
good point
not sure what causes the error though, you're effect list template is a list
Managed to find a forum topic on that: https://community.home-assistant.io/t/template-light-help/397554
I dont get why, but adding effect_template: "" fixed it, even though I assume its the default?
I'm trying this, but keep getting errors:
ValueError: Template error: strptime got invalid input '2023-02-08 14:55:37.890084+01:00' when rendering template
No the default is none which is not the same as ""
First use as_datetime to convert the string to a datetime
{{ as_datetime(o1) }}```
Gives TypeError: float() argument must be a string or a real number, not 'datetime.datetime'
Wait, what is your goal here
You should be using strftime, not strptime
strptime is used to convert a string to a datetime, you already have a datetime
strftime is used to convert a datetime to a string
I have a sensor (sensor_tesla_time_to_full_charge) which reports the time till a full charge as H.MM (for example 1 hour 30 minutes is 1.50). I would like to know not how much time is left, but at what time it is fully charged.
Sounds like it's the number of hours
{{ now() + timedelta(hours=states('sensor.name'))|float }}
It doesn't show the time as H.MM. it just shows the time in hours
And what Rob posts should indeed work, maybe in combination with strftime
hello good people, I was wondering if someone could help me troubleshoot this weird issue I'm having trying to get my LG C2 TV to turn on (and off) with a script.
woops, wrong channel
@full nacelle I converted your message into a file since it's above 15 lines :+1:
Why is this showing an error "Invalid config for [media_player.universal]: [entity id] is an invalid option for [media_player.universal]. Check: media_player.universal->commands->turn_on->entity id. (See ?, line ?)."
what problem?
oh hey petro, it's me again 🙂
@quasi widget I converted your message into a file since it's above 15 lines :+1:
this is the script
it works fine if I start executing it while the TV is turned on, I can get it to turn on and off repeatedly, no problem
because, entity_id is not a valid option for turn_on
however if I turn it off and walk away, come back to it a couple of hours later, it won't turn on again
@full nacelle look at your turn off service... it's correct. Then look at your turn on service
note the differences
can I use something so I can call an entity there?
it is a button that I want to call.
That sounds like an issue with your hardware
when it's in a deep sleep
that's what I'm thinking, but I'm pretty sure I have all the right options enabled in the TV's settings
did you copy/paste that configuration? Do you understand what each section means and how it works?
guess I'll look into it further, I just want to make sure the script is set up right ... which since it works in the moment, it should be
I'd start by looking on LG forums
I do understand how they work
ok, so do you understand why turn_on is incorrect and why turn_off is correct?
I tried it with the media player thing, it doesnt work
I made a wol for it
but it seems cant call it
I still have no idea if you understand what I'm talking about
You pasted a snippitof your code
I edited the temp from website
This command in your configuration is wrong
turn_on:
entity id: switch.lg_tv
This command is correct
turn_off:
service: media_player.turn_off
target:
entity_id: media_player.arun_s_webos_tv
Can you see what the differences are to know enough to make a change to the turn_on command?