#templates-archived
1 messages Β· Page 56 of 1
I forgot to update you on what I did. I deleted my first attempt, the one with the error, and recreated it. It is still a template sensor with the same ui then when I created it when I open the helper up again.
you aren't understanding
I am not, you are right
Are you using the UI to create this entity? Yes or No?
Yes
Ok, then you cannot make a trigger based template sesnor via the UI
So, the behavior of your template sensor will be different
I can not find good examples online to create this kind of template sensor that are in the new style of script. It really trips me up attempting anything remotely advanced in yaml atm :/
I see
Also, because you're creating a new sensor that has a different unique_id, it** will not replace your existing entity.** That means you're old entity will remain and will have an unavailable state. Your new sensor will have a new name and entity_id.
so theres 2 things your doing wrong
- Looking at the wrong entity
- expecting the behavior to be the same
Yes it is called the same. You said what was wrong. What do you propose I do to make this work? Do this in yaml editor?
why are you recreating it, just keep your old one
I don't know petro. I am experimenting and trying things that might work to create experience.
I am working with limited knowledge here. I am learning π
When I pasted and changed TheFresses example in my sensor yamls, I got a ton of errors. I disregarded the idea that TheFes made mistakes and assumed I was using it in the wrong spot.
it should not be in sensor.yaml
Alright that's what I thought. But also not in helpers?
the first line is template, not sensor
you can put template: !include templates.yaml in your configuration.yaml and put it in templates.yaml (remove the first line with template: though)
okay, that's where it should be then π
Yes it feels right at home there
It's purring along as a test and I am now trying to make a statistics graph from it but it's not letting me check any stat type
I want to show one card that displays the number of liters pumped up live when it is pumping and reset every day and I want do display a bar graph of pumped amount per day.
you need to add at least a unit_of_measurement but I would also add state_class: total_increasing
I do have unit of measurement, device class and now state class
What is it called again; to drop the numbers after the comma? I want to add that too
Fantastic! State class did the trick! I can now show changed state on a daily basis with bars
Hi, could someone help me on how I can make a condition that check if the value into my nest thermostat target_temp_high and compare it with a numeric field?
what is the correct syntax to check for a string inside a calendar event title in an automation with a calendar event trigger? I know I have access to the trigger.calendar_event.summary variable but cant figure out what the function is to check for the required string.
{{ 'foo' in trigger.calendar_event.summary }} @cursive berry
Could You please help me on esphome. My homeassistant has been installed on raspberry pi 4. I have a temperature sensor that connected to esp32 via SPI and that esp32 connects to Homeassistant. I have a another esp32 in aanother location. I want to read that temperature and out put that value on esp32 uart for experiment. I may attache a large seven segment later. I tried to do this with esphome assistant custom cocomponent so i could write arduino code in as seperate include file. But didnt work. It says temperature sensor id is not in this scope . Couldn't you Please tell me the proper way to do this. Thank you.
Hello π
I need a little bit of assistance with a template π
User input malformed: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'float') for dictionary value @ data['state']
Are you going to share your template?
{% set energy =
states('sensor.kwh_24_hours')
%}
{% set house =
states('sensor.heat_pump')
%}
{{ ((energy - house)) }}
{{ states('sensor.kwh_24_hours')|float(0) - states('sensor.heat_pump')|float(0) }}
States are strings. You have to convert them to numbers before doing math with them.
You should use an availability template as well if you are going to use this with the energy dashboard.
availability: "{{ has_value('sensor.kwh_24_hours') and has_value('sensor.heat_pump') }}"
It works π What does the availability do?
No, I am not very happy with the energy dashboard so I am working on making my own
But that error didn't came from that template, there is no float in that template, so it can't be that one.
That template would have given TypeError: unsupported operand type(s) for -: 'str' and 'str'
Hi guys
how can I know the amount of active persistent notifications? I used to have this template but for some reason it stopped working after updating
{{states.persistent_notification | length }}
I don't see persistent notifications as entities either...
that's right, those have been removed a couple of months ago already
I know @floral shuttle had issues because of this as well, he might created a work around for it
Thanks for the template π It works perfectly just the way I need it
Yep I did! I will post the package when back at the desk
btw here's the topic in the community where the joint effort was created https://community.home-assistant.io/t/heads-up-2023-6-longer-has-persistent-notifications-in-states-what-to-do/578654/135
this consists of a trigger template which you can use to show the notifcations in let's say a markdown, and count them. Next to the counter, I also made a binary sensor for any alarm on existing notifications in the UI, and lastly, I built a system where a boolean is toggled per notification (as stated in the yaml you need to create those manually) and then can show individual card with alarms on those. Or, dismiss the notifications by means of those booleans
fixed file name
changed my expand templates to use state_attr() and see startup errors on these {%- for s in state_attr('binary_sensor.active_devices','entity_id') if states(s) == 'on' %} {%- if states[s].last_changed.day == now().day %} {%- set stamp ='%H:%M' %} {%- else %} {% set stamp = '%d/%m - %H:%M' %} {%- endif %} {%- if loop.first %} {% else %}, {% endif -%} {{states[s].name}} ({{as_local(states[s].last_changed).strftime(stamp)}}) {%- endfor %}
bottomline:homeassistant.exceptions.TemplateError: TypeError: 'NoneType' object is not iterable
do I have an obvious mistake here?
same goes for bject of type 'NoneType' has no len()') while processing template 'Template<template=({{state_attr('switch.critical_switches','entity_id')|count}}) renders=4>' for attribute 'aantal' in entity 'sensor.kritieke_schakelaars_samenvatting'
so even though these templates check a core ha helper group, they are not available on startup? after startup they populate correctly
No obvious mistake but there's no reason to change that from expand.
you're accessing the state object in the first one, that should remain expand
the second one you can use {{(state_attr('switch.critical_switches','entity_id') or [])|count}}
originally I had {%- for s in expand('binary_sensor.active_devices') if s.state == 'on' %} {%- if s.last_changed.day == now().day %} {%- set stamp ='%H:%M' %} {%- else %} {% set stamp = '%d/%m - %H:%M' %} {%- endif %} {%- if loop.first %} {% else %}, {% endif -%} {{s.name}} ({{as_local(s.last_changed).strftime(stamp)}}) {%- endfor %}
and that never threw errors. However, TheFes figured why expand to the full state object, not required, so this would be faster/more efficient?
my counters were also simpler:{{expand('binary_sensor.active_devices')|count}}
but again there, why use the full object if not perse required, causing more memory usage?
the only way you'd make it faster is if you actually make use out of generators
which you aren't doing, so it doesn't matter
for testing purposes I added that same or [] to the other templates, and all startup errors are gone.
just keep in mind that only works when state_attr returns None
ok noted. as was the case here.
thanks - had tried that but wasn't working and ended up needed to do a restart
I love HA. It's got the greatest ability to break the simplest things and make you nuts in order to fix them.
It's easier to just turn on/off the lights manually than keeping HA updated lol
thanks you all
I'm selling everything
I too joke with my colleagues that the time I spent tweaking/tuning/etc. is easily equal to years of walking to the light switch π ... but it is also fun and HA does a lot more than just switching lights, it is now my central hub for a lot of things that otherwise require me to go to dozens of sites with various logins etc.
I have a binary sensor created manually that I want to disable at times. I have been told the only way is templating it into another sensor. Can someone advise how to do that?
- platform: ping
host: 192.168.1.159
name: LG TV Online
hey
can someone help me on this
Hey can someone help me to create a sensor? Basically i have 2 sensors. One that tells me it the energy is reverser or forward and another that tells me the energy What i need is if the sensor.direction == reverse the energy value should be negative if it is forward should be positive. I try so many things but i cannot make it work. and somethimes other sensors stop work :/
You mean disable the entity itself?
if yes, you have to use the spook integration
it's custom
yeah. But tbh I just found that I won't need it.
I was told that, but I thought there would be an alternative, as I don't feel confident enough to install that xD
the alternative is manual enabling/disabling
can't be done for yaml sensors, that's the thing.
@celest bone I converted your message into a file since it's above 15 lines :+1:
then your only option is spook
{% set value = states('sensor.energy') | float %}
{{ iif(is_state('sensor.direction', 'reverse'), -value, value) }}
You can make it unavailable whenever you want
Is there a way to pull out the next event time (or time until next event) for a specifically named recurring event on a Local Calendar?
For example, if I have a calendar with "Event A" recurring twice a week and "Event B" twice a month, is there a template I can use to create template sensors to tell me when the next "Event A" and when the next "Event B" is? Or do I need to use separate Calendars for that?
how? Just out of curiosity
Using an availability template
He wants to stop the functionality of the ping sensor,
that can only be done by disabling the entity
manually or with spook
yeah okay, you could create a template binary sensor out of it, and make that one unavailable. But to disable it you need to use spook or do it manually
Is it possible to use this while creating a list in a template```
states.light | << other selectattr >> |
selectattr('last_changed', 'lt', '10') |
map(attribute='entity_id') | list }}
last_changed is a datetime, so comparing it to 10 doesn't make sense
Thx - Did a crude work around, still to be tested... fingers crossed. My aim is to create a list of lights that turned off in the last x amount of seconds that I can then pass to a service as the entity_id target
then you want something like selectattr('last_changed', 'lt', now() - timedelta(seconds=10))
or maybe selectattr('last_changed', 'gt', utcnow() - timedelta(seconds=10)), since I think it's in UTC
Thank you! Much cleaner as the solution I currently have π
you want gt if you want the lights turned off in the last 10 seconds. I changed it
Appreciated... My brain is fried now - Will finish up tomorrow, also discovered that my automation bombs on the conditions. The error in the log says: In 'template' condition: UndefinedError: 'list object' has no attribute 'startswith' In```
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.startswith('light.browser') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.endswith('doorbell_flash') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.endswith('control_screen') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.endswith('control_screen') }}
- condition: template
value_template: >-
{{ not trigger.event.data.service_data.entity_id.startswith('light.swimming') }}
The triggers do seems okay in the trace```
trigger:
id: '0'
idx: '0'
alias: null
platform: event
event:
event_type: call_service
data:
domain: light
service: turn_off
service_data:
entity_id:
- light.master_bedroom
- light.master_bedroom_led
Its most likely because it is a list and not a single entity
Will perhaps move the conditions to the actions in a repeat or something similiar
My starting point will be TheFes's suggestion of using this:```
variables:
trigger_entities: >
{% set e = trigger.event.data.service_data.entity_id %}
{% if e is not string %}
{{ e }}
{% else %}
{{ [e] }}
{% endif %}
that would do it
Whatβs the right way to store a data table in HA? I want to set up some template sensors to calculate eg temperature anomalies versus a long term average which I have as say a table of floats with a row for each of the weeks of the year.
@ember otter I converted your message into a file since it's above 15 lines :+1:
uh ok lol, don't think that was necessary but sure
will further note: i've already reloaded config, restarted HA, checked FAQs and documentation, etc... about all I can say is that I'm probably glancing over the obvious answer like an idiot lol
Where did you place this?
in the configuration.yaml. is that not where they are supposed to go?
okay so I finally got something to show up as an entity but it didn't show as available at first - turns out something was being misunderstood with the availability template? so I just replaced it with
{% if is_state('binary_sensor.garage_available', 'on') %} yes {% else %} no {% endif %}
of course I have yet to test if the template cover works...
yep it works!*
* -it clearly still has a problem with not differentiating between the door being stopped & the door closing/opening, but that's a problem for tomorrow morning, it's 1AM and I can't be bothered rn lol, I achieved my goal of making an entity that triggers the button & displays the current status of the garage so I'm satisfied for now
You can just use {{ is_state('binary_sensor.garage_available', 'on') }}
That will return true or false which is what it expects
i think that's what I did first, but it then caused the template cover to forever be stuck unavailable, even though the entity was not in that state
this will change the current value or it will create a new sensor ? I am really new on this :/
Should work fine
You can't change the value of the source sensor, you have to create a new sensor which uses the data of the source sensor
so it should be something like this ?
- name: "Energy Direction"
unit_of_measurement: "kW"
value_template: >-
{% set value = states('sensor.energy') | float %}
{{ iif(is_state('sensor.direction', 'reverse'), -value, value) }}
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.
If it's energy I would expect kWh
i will try
@thorny snow I converted your message into a file since it's above 15 lines :+1:
do you feel it is ok ? π
when i add this new sensor every sensor into this template stop work
Compare the first one with the second one
You are using state in the first one, and value_template in the 2nd
value_template is used in the legacy format, which you are not using
Hey there,
I got a hommatic hm-es-tx-wm to track my electricty statusmeter (consumption and returning to grid). Unfortunately I only get the overall values in kWh and the current values in W. So my energy dashboard displayes a daily consumption of e.g. 25000 kWh... How can I get the difference from yesterday to now to display the todays consumption in the energy dashboard?
The historic data is persisted. So If I open the sensors details I can see past values.
This is something for #energy-archived
In basic a lifetime sensor is best for the Energy Dashboard
I thought that the energy dashboard displays the daily values.
But I will move this there. Thanks
stipid question... Why i dont see this sensors in my ha after reload and restart:
[core-ssh config]$ grep sensors configuration.yaml
sensor split: !include_dir_merge_list includes/sensors/
[core-ssh config]$ cat includes/sensors/energy_sensors.yaml
# sensor:
- platform: template
sensors:
tuya-zmywarka_voltage:
value_template: >-
{{ states.switch.zmywarka.attributes.voltage }}
unit_of_measurement: "V"
... invalid slug tuya-zmywarka_voltage (try tuya_zmywarka_voltage)
how can i do this Developers Tools > Check config from CLI or VSS code extensions?
yes, i resolve my problem with - in name... but how can i execute check config from CLI? ha os check dotn show this errors
To check your configuration use the command for your install method:
Evening All, I've got an automation that triggers based on any update to an entity but I need to ensure the automation doesnt run if the previous state was unavailable / unknown.
Can I use a template condition with {{ trigger.from_state.state not in ['unknown', 'unavailable'] }} for this?
Or just add this to the state trigger
not_from:
- unavailable
- unknown
But your solution would also work
Would that go in the yaml of the trigger?
Thank you π
hi, can I use the 'this' (described here) object in a condition of an automation? If so, hwo is it refernced? 'this.state.attributes' or something else?
this in and automation will refer to the automation itself, if you need the attributes you will need to use this.attributes
sensor:
- platform: rest
resource: https://api.nasa.gov/planetary/apod?api_key=API_KEY
name: "NASA Astronomy Picture of the Day"
scan_interval: 3600
value_template: "{{ value_json.hdurl }}"
Hi all, I keep getting a "'value_json' is undefined" error when trying to get the picture of the day from NASA's API. I can access the URL just fine with curl. What is the issue here?
works fine with me, maybe blocked as this seems to be a "picture of the day" and you refresh every hour?
Hm without the interval I still get "unknown"
and in the template editor I get the JSON eror.
error when you use the json ?
I mean when I put this code in the Template Editor of the Developer Tools section
and if you are blocked, removing the interval will not help
which code? the one with the url? that will not work of course as template editor will not get the json
ah so I cannot test it there?
can I test it anywhere else before putting it in my YAML files
without having to restart HA each time
you donot need to restart... in devtools/yaml you can reload the rest but again, above works fine for me so I think you have another problem, maybe too often, maybe your HA server has a hick-up on this address?
you can put logging to debug for rest, restart HA and then see if more is shown
other wise you can use the url in browse, copy the json in the template editor and setitng it simialr as the one that is shown by default...then add your sensor from above and see what happens...again, from my pov it is not the sensor
I'll try this
Thanks π
ah it works now!
but still, just reloading YAML made the sensor disappear
when I fully restarted again, it suddenly showed up with the correct information
I am finding that where this works fine:
condition:
condition: template
value_template: |-
{% from 'logic_chekr.jinja' import true_all %}
{{- true_all( ['binary_sensor.dark_outside'] ) | bool -}}
This does not. This renders a true and the execution stops with the shortcut syntax.
condition: |-
{% from 'logic_chekr.jinja' import true_all %}
{{- true_all( ['binary_sensor.dark_outside'] ) | bool -}}
Can anyone else verify that the custom templates cannot do the shortcut notation, or did I mess that up syntax wise.
No HA errors I do not believe.
Update... Check that, there was an error...
while parsing a block mapping in "/config/./automation2/Outside_A2.yaml", line 5, column 5 expected <block end>, but found '<scalar>' in "/config/./automation2/Outside_A2.yaml"
Hello, could someone help me with some Jinja? Is this the place?
right place
I have this codnition that does somethign when a condition is met
{{is_state_attr('sensor.octopus_energy_electricity_xx_xx_current_rate', 'current_day_min_rate', states('sensor.octopus_energy_electricity_xx_xx_current_rate')|float)}}
How do I trigger something if it is not true?
Is that the condition section of the automation itself? That doesn't take short hand directly
Hello together. @marble jackal helped to modify a blueprint, thanks for that. I want to extend it, but i am not sure, if this is the right way. What do i want to achieve: We have a lot of danfoss ally room thermostats, which could be updated in "covered" or "uncovered" mode. For both situations, it is needed to update the temperature from time to time. For the covered mode, which i prefer, it is needed to update the time -> minimum 5 minutes AND more then 0.1 degree temperature change OR when the timer is finished if there is no temperature change. with the first blueprint, only min timer works. The same is for uncovered mode, but with different times cycles. I think there is something wrong with the timer at my try, which seems not to be defined and not restarts, if fired from event. May someone take a look at it? π
original one: https://dpaste.org/tOVPt
modified one: https://dpaste.org/UeqQP
@full crescent This would work
condition:
- >
{% from 'logic_chekr.jinja' import true_all %}
{{- true_all( ['binary_sensor.dark_outside'] ) | bool -}}
Put not in front of it
{{ not is_state_attr() }}
TheFes: I've copied your brilliant https://github.com/TheFes/HA-configuration/blob/main/include/integrations/packages/tgtg_notificaton.yaml but is there a way to only be notified when one favorite has state above 0? I'm getting notifications from one shop here that they have 15 left and then 9 left and the 4 left etc. π
g'mornin yall. I have an auto-entities card that I'd like to list all entities with regex; "/^media_player(.).*_mrp_active/" doesnt seem to work - can someone point out what I have wrong?
I spoke too soon - I dont know what it was doing
how come my template which i saved as a template itself is working and giving me a percentage output, but my automation does not react to it?
@full crescent I think my indentation was wrong before, I changed it above
Hmm.. Maybe someone has an idea why i get this error? From my understanding, max update timer is defined!?
Executed: 16. Oktober 2023 um 14:56:42
Error: In 'template' condition: UndefinedError: 'max_update_timer_id' is undefined
is this about the modified blueprint above?
yes, the one you helped me with. i tried to extend it π https://dpaste.org/UeqQP
The error is a bit strange, as it is one of the input selectors
well, it does not work π
i am also not sure, if the modifications i made, make sense how i did them.
If temperate difference is above 0.1 degree AND timer is above 5 minutes, then make action. OR maximum timer time reached if no temp difference is happening , also fire the action, which should set a new time and gives a timer loop.
Step detaills shows me:
Executed: 16. Oktober 2023 um 15:13:42
Error: In 'or' (item 2 of 2): In 'template' condition: UndefinedError: 'max_update_timer_id' is undefined
conditions/0
Executed: 16. Oktober 2023 um 15:13:42
Result:
result: false
conditions/0/conditions/0
Executed: 16. Oktober 2023 um 15:13:42
Result:
result: false
entities:
- sensor.average_temperature_badezimmer
- number.tcv_badezimmer_external_measured_room_sensor
conditions/1
Executed: 16. Oktober 2023 um 15:13:42
Error: In 'template' condition: UndefinedError: 'max_update_timer_id' is undefined
at the template editor i also get this error!?
'timer' is undefined
{{ states((timer.timer_badezimmer), 'last_triggered') }}
{{ states(("timer.timer_badezimmer"), 'last_triggered') }} ?
Thanks @obtuse zephyr it found the timer now! Will reboot HA and hope that it works now π
still extra parenthesis
Hmm.. Now i git this error:
Error: In 'template' condition: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'
state_attr fixed it.
:\ Whatever i do - now the timer is always "true" - it doesnt matter if the time is running or running out. i tried two things:
value_template: >
{{ as_timestamp(now()) - as_timestamp(state_attr("max_update_timer_id",'last_triggered'),0) < 60 * "max_update_minutes" }}
value_template: >
{% set last_trigger = states((max_update_timer_id), 'last_triggered') %} {{
last_trigger is none or now() - last_trigger >
timedelta(minutes=max_update_minutes) }}
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.
the quotes around max_update_timer_id in the first one are wrong, that makes it a string, and not a variable
your are still using double paranthesis in the second one
and I just tested with a timer of myself, it doesn't have a last_triggered attribute
oh wait, you are using states() not state_attr()
what are you trying to achieve with that last_triggered part?
you are using state_attr() in the first one and states() in the second one
@thorn harness can you explain in words what your goal is with this template
I would like to do:
If temperate difference is above 0.1 degree AND timer is above 5 minutes from timer, then make action. OR maximum timer time 30 minutes is reached if no temp difference is happening , also fire the action, which should set a new time and gives a timer loop.
there is no attribute in the timer which stores when it was last finished
you can see if the timer is idle
so only chance is, to compare time
Sorry, I have to go now
Np π Thanks for help!
having a blonde moment; what's the right way to get a state attribute in JS? using it on a custom button card -- I keep getting [object Object]
... smh
i got it
Just want to make sure I am right, but markdown card titles are not templatable, right?
yeah doesn't look like they are. only the content.
hey @lofty mason, have you ever used the config-template-card?
no
it looks cool as hell, but Im not sure I can get it to do what I want
was hoping someone had some experience with using it
ask in #frontend-archived , I'm sure someone has used it.
that might be better -- it's kindof a mix with templates too and I usually get good advice here. (just like now)
The indentation wasn't my problem, that fixed itself instinctively in my head. I just never thought of pulling that to a bare list like that. It is working just fine. Thanks for the help.
Forgot the .state? π I just did that recently a couple of times, too...
lol actually it was .alerts -- was creating a nws card for active noaa alerts in the area
since then, I've literally given myself a headache trying to figure out how to pull apart something interesting I found with creating dynamic cards to go into a swipe card for the alerts that come up
has pretty much been an all-day escapade, and I just now got it to make 2 buttons. lol
this is the "something interesting": https://www.reddit.com/r/homeassistant/comments/116fmju/create_multiple_lovelace_dashboard_cards_in_loop/
basically going to take the nws alerts and create a single card per page on the swipe card with the alert info
if my head doesn't explode first
Hi everyone, I want to find out if my gas heating is currently running or not. I already have set up a counter for the gas consumption and get this properly. Based on that I also calculate the kWh consumed. Now I want to have a status display if the heating is currently on or not. My idea was to do this with a derivation helper variable on the gas consumption counter (based on 1 min). If this derivation helper is greater than zero than I could set a binary template sensor to "on", otherwise it is off. However, I am a total newbie on Yaml and Homeassistant still. Could anyone let me know where I product the error in the template?
-
binary_sensor:
- name: "Status Gasheizung"
unique_id: status_gasheizung
state: >
{% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}{% if ableitung_gasverbrauch > 0 %} {{'on'}} {% elif ableitung_gasverbrauch = 0 %} {{'off'}} {% endif %}
you used ">", but didn't actually provide a multiline template
And that was the error in the log:
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got '=') for dictionary value @ data['binary_sensor'][0]['state']. Got "{% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}\n{% if ableitung_gasverbrauch > 0 %}\n {{'on'}}\n{% elif ableitung_gasverbrauch = 0 %}\n {{'off'}}\n{% endif %}\n". (See /config/configuration.yaml, line 164).
And how do I do this?
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.
- binary_sensor:
- name: "Status Gasheizung"
unique_id: status_gasheizung
state: >
{% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}
{% if ableitung_gasverbrauch > 0 %}
{{'on'}}
{% elif ableitung_gasverbrauch = 0 %}
{{'off'}}
{% endif %}
Thanks for the hint ...
template:
- binary_sensor:
- name: "Status Gasheizung"
unique_id: status_gasheizung
state: >-
{% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}
{% if ableitung_gasverbrauch > 0 %}
on
{% elif ableitung_gasverbrauch == 0 %}
off
{% endif %}
you didn't provide a case for when it's negative, but if it can't be negative, it's even easier
template:
- binary_sensor:
- name: "Status Gasheizung"
unique_id: status_gasheizung
state: >-
{% set ableitung_gasverbrauch = states('sensor.ableitung_gasverbrauch') | float %}
{{ ableitung_gasverbrauch > 0 }}
Thank you RobC. Will give this a try....
It works! Thank you very much. Now I just need to do the display on the GUI based on that! Thanks a bunch!
the == was missing in my part ... and yours is a lot leaner!
Hey Rob, trying to combine 2 working templates - the first one creates my swipe card, and the other is the a for loop that lists all the nws alerts. I've removed the pagination and extra stuff to make this fit on here, but Im curious how I can get the foor loop where cards: is supposed to go
{%- set ns = namespace(results = [{
"type": "custom:swipe-card",
"cards": ""
}])
-%}
{{ns.results}}
Finally i got the danfoss ally automation to work. π Thanks all for your help. π Is it somehow possible, to add a condition, that the automation will not fire when temp sensor is 0? I use some average sensors for those thermostats, after home assistant run, they will be 0 for a few seconds. Something like if temp sensor is zero or not availabe? https://dpaste.org/7cNL7
As I am new to HomeAssistant I sometimes do not know on how to best solve a problem. I want a simple display if my gas heater is running or not. The gas consumption in kWh is working reliably. However, my approach to do a derivation helper on the last minute to check if it is running or not is not working properly. The derivation does not go back to zero if energy consumption (total increasing) remains constant. How could I simply check if the value of my total energy consumption now vs. 1 min ago did not change and then set the status accordingly?
@thorn harness 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.
@mellow sigil I converted your message into a file since it's above 15 lines :+1:
you don't have a template there, so it doesn't belong under template:
not everything is a template π
erm OK, then how can I write the equivalent of the derivate helper in yaml?
can i get the code for an existing on which works?
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
that describes what a template is
you second example looks fine
what do you mean by
but I've no way to see this "sensor" like creating a Card showing it's value.
it should create a sensor entity, and you can display that
no I can't "see" it anywhere.
Of course I know I've to reload the configuration and did.
To check your configuration use the command for your install method:
I checked it, green.
and you "see" it in
-> States, and in the entity picker of whatever card you're using (if it provides one)
reloading YAML won't be enough if you didn't already have sensor: in your configuration.yaml
you would need to restart HA
I already have, yes
ohhhhhhhhhh - let me try
it's restarting... while this, is there a way NOT to reload for every sensor I'll create?
yes, via
-> YAML
and you don't need to use YAML at all if you just create helpers in the UI
then you don't need to reload anything
I wish a specific one, like for the format displayed etc - this test above is just a basic one, but I'd wish something more personnalized than the UI
I don't understand yes via YAML, you mean, you can YAML an UI created derivative? let me check...
I didn't follow that
Thank you - cnfirmed, it's now showing in States or for creating a Card, it works! thanks!
I mean, now I wish to make other sensors, should I restart every time??? Is there another way, or file, to put them?
what part?
- platform: derivative
name: TestCurrentPower
source: sensor.lixee_current_summ_delivered
round: 3
unit_time: h
unit: kW
time_window: "00:01:00"
I don't know what you're asking
you asked if you need to restart HA every time you add a new sensor, and I said no
and what to do instead of restarting
is there still confusion?
ok, but then why did I had to restart HA a few minutes ago (and it worked, thank you again, a million!)
because you added sensor: for the first time, so it wasn't loaded at all
ah no, I already had a sensor:, this was my second
ok
this is what's in configuration
sensor:
-
platform: group
name: GroupMeasuredEnergy
(etc) -
platform: derivative
name: TestCurrentPower
source: sensor.lixee_current_summ_delivered
round: 3
unit_time: h
unit: kW
time_window: "00:01:00"
any time you add a new sensor:, paramecie, you'll need to reload the yaml that goes with it
please stop posting unformatted code
ohhh sorry
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.
anyway, doesn't matter. you can reload YAML via the method I mentioned
what RobC is saying is that once the sensor is created, you can reload the templated sensors without reloading all of HomeAssistant
I did it, ten times trying many things - no way to see the sensor, only after the restart of HA it worked
right. because you have to initialize the sensor: with a restart of HomeAssistant
every time you add a new sensor
sorry but no, it's my second sensor, the first works since yesterday
if you modify an existing one, then reloading the templated entities will only apply to the sensor: 's already loaded
right. the second one is new
so you had to reload HA
ohhhh you mean for every NEW (only) sensor, you've to restart HA?
otherwise only YAML reload?
correct
no
so, I'm not sure I would have found this written somewhere, especially not knowing what the problem was π
A MILLION thanks both. Please have a nice one!
You're welcome. (and I still owe you a couple, RobC)
lol
esp. after my debacle of a template
BTW... I've a few sensors in templates.yaml with work very well, no problem.
Why for this derivative it can't be a template?
What's in short the difference in between a sensor in template (that I can show in a Card) and a sensor in configuration.yaml sensor: (that I can show also). This is a bit puzzling.
there's simply no template there
if you want a template sensor, you need to create a template sensor
no, all I want is basically sensors, but put some in template
then make a template sensor that references the other sensor
there are many examples in the docs: https://www.home-assistant.io/integrations/template/#examples
you can't just add a template to some other sensor. you can create a template sensor that derives its state from some other sensor
I'm not even sure what you're trying to do. Why do you want a template?
I mean, they're cool, but why?
still don't get it... this is a sensor? I put it in templates.yaml:
- sensor:
- name: TempoToday
state: >-
{% set tempo = states('sensor.lixee_active_register_tier_delivered')%}
{% if tempo == 'HPJB' or tempo == 'HCJB' %} BLEU
{% elif tempo == 'HPJW' or tempo == 'HCJW' %} BLANC
{% elif tempo =='HPJR' or tempo == 'HCJR' %} ROUGE
{% else %} Error
{% endif %}
presumably that's under template: and is a template sensor
arf - I still don't understand what's a template vs what's a sensor
they aren't mutually exclusive
that is a template sensor
template sensors derive their state from a template, as you just showed
other types of sensors derive their state from something else, like the derivative sensor that you showed earlier
they are both sensors
template sensors used to fall under sensor:, as shown at the bottom of this page: https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
ohhh I thought template as in "template of a sensor" something like a model you can apply to a sensor, multiple sensors
no, it's not that kind of template
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
ohhhhhhhhhh
I think he got it, just backwards
yep π
you apply the template to the sensor
"template" is Jinja terminology
not the sensor to the template
you're champs people, thanks - but I've been disturbed by the "template" wording
How do I use a "or" condition in jinja? Iam confused, that I cant find a answer with Google ^^'
literally "or"
is there a good way to have a sum helper not become unavailable when one or more of the child entities be unavailable but return a default value instead?
if you want to continue to use your sum helper, then you can create a template sensor to assign a default
{{ states('sensor.sum_sensor')|float(0) }}
i see thanks!
@inner mesa @languid pendant Very sorry people, but following the above conversation, and about templates (was confused) and the fact I've to restart HA when I create a new sensor in configuration (yaml)....
My problem is, I tried to change an existing (same as above) sensor either source: or unit:, but even reloading YAML twice, or "quick rebooting" reloading the yaml, the changes aren't effective.
I tested, I have to restart HA for any change to an existing sensor in configuration π¦
Is this normal? It's pure pain, sincerely, especially with sensors like derivative as the numbers are crazy for some time after the restart...
What am I doing wrong? Is there an add-on (i've HACS) or sometheing that could help?
ALL - the first choice
try template entities
it's not in templates, it's in configuration.yaml - let me try anyway
it doesnt matter where theyre defined, theyre still templates.
nope - I even CTRL+F5 the pages
I checked in both States and on my Card, it shows for example the previous unit: not the new one
if you have templates defined in configuration.yaml, or templates.yaml, you can reload the TEMPLATE with template entities
if you are attempting to change the core sensor data, you have to reload HA
no, I've "sensor:" defined in configuration
ok,
but then, if the problem is because it's not a template... can't I make this derivative a template?
sensor:
- platform: weatheralerts
state: AK
zone: 827
county: 290
^ this is a sensor. I have to reload HA when I change the data
Is it
- platform: template```
or
```template:
- sensor:```
sensor:
- platform: template
sensors:
wc_temperature:
friendly_name: "weather-card temperature"
value_template: |
{{ state_attr("weather .kged_daynight", "temperature") }}
^ this is a template
it is (sorry, I don't have backticks on the keyboard):
sensor:
-
platform: group
name: GroupMeasuredEnergy
(etc) -
platform: derivative
name: TestCurrentPower
(etc)
(etc) should be on a new line
Those sensors need a HA restart
That's Frankencode
oh dear lord π¦
can't I make a derivative in template, or another way in some code, but not in UI?
@marsh cairn lol i know it's the first thing i could grab
Not Frenckencode I hope π
Hehe
good lookin out
A legacy one
Not obsolete - it still works. But the new format is recommended
still works; havent gotten around to updating those as theyre just for a weather card
Yes, Visual Basic 6 still works you know?
π
Sorry to tease you.
(and I'm still using it on a dedicated machine)
Anyway, the question: "can't I make a derivative in template, or another way in some code, but not in UI?"
HAHAHAHA ... hey now -- I used to work for a company who wrote (and still writes) an ERP in visual basic for their production
That's exactly what we do π Have new servers, node.js and such, but still old tools - still working like a charm
@mellow sigil, start here: https://www.home-assistant.io/integrations/template/
read, then re-read. then read again.
and really, what re you trying to template, exactly?
what data are you trying to pull from your derivative sensor
I haven't followed your conversation for long. But why not in UI and why not letting the YAML one do its thing after a HA restart?
Already read!
A simple template or sensor of a derivative, the base being:
- platform: derivative
name: TestCurrentPower
source: sensor.lixee_base
round: 3
unit_time: h
unit: kW
time_window: "00:01:00"
@marsh cairn because i wish to make some calculations and changes which aren't proposed in UI - thanks to help Jorg
I made this derivative in UI (another name) works fine. Same in YAML. But just the restart is pure pain.
{{ area_id('binary_sensor.living_room_motion')
| area_entities('bedroom')
| expand
| selectattr('attributes.device_class', 'eq', 'illuminance')
| map(attribute='state')
| map(int)
| average }}
Trying to get the average lux in a room but getting this error with the above template: TemplateRuntimeError: No filter named <function forgiving_int at 0x7f0682247240>.
map('int')
wow, gg Rob
Usually you don't touch your sensors too often. The ones which weren't able to be quick-reloaded didn't bother me that much.
agreed @marsh cairn - just the dev time is made longer and a bit painful
ok then, and again, thank you all Rob, Deadly, Jorg... ring me if you think at something π thank you
@inner mesa trying to add items to this list and reference it as such list later, but doesnt seem to work without being a namespace, is there no other way?
{% set ns2 = [] %}
{% for event in state_attr('sensor.st_lawrence_island','alerts') %}
{% set ns2 = ns2 + ['test'] %}
{% endfor %}
ns2 returns []
yes, it looks like you tried to use a namespace, but didn't actually do it
right. so when i use this:
{% set ns2 = namespace(cards=[]) %}
it works, but when I reference, i get this: [{'type': 'custom:swipe-card', 'parameters': {'pagination': {'type': 'bullets'}, 'spaceBetween': '8', 'effect': 'fade', 'fadeEffect': {'crossfade': 'true'}}, 'cards': <Namespace {'cards': ['test']}>}]
ooh. i have to use ns2.cards... maybe
i think
yes
I'm trying to use a REST sensor to get info from an Arylic music amp. It returns strings as hex, eg "4920446F6E2774204B6E6F7720416E797468696E67". How do I convert from hex to ascii string in the value_template?
It seems like there is no unhex function for templates
Good morning. I have a working automation with the following timer trigger. I would like to change to this to a more elegant solution, to survive reboots. Is it possible to use the last changed attribute with a timer? @marble jackal already told me, that there it is not possible this way. Maybe someone has a hint, what to look for?
(this.entity_id) is the entity of the automation.
this works:
value_template: >-
{% set last_trigger = state_attr(this.entity_id, 'last_triggered') %} {{ last_trigger is none or now() - last_trigger > timedelta(minutes=min_update_minutes) }}
this i tried ( gives me always true !?):
{% set last_changed = state_attr("timer.timer_buero", 'last_changed') %} {{ last_changed is none or now () - last_changed > timedelta(minutes=5) }}
to access the last_changed datetime, you need to use states.timer.timer_buero.last_changed
but as I already mentioned, it will reset after a restart
but I don't understand why you are so interested in the time the timer changed state?
it will either be idle and then it's not running anymore, or it is not, and then you can calculate the start time (if that's what you need)
Well, you are right. It would just be a cosmetic thing π I let it how it is now. I published the working blueprint now for the community, it works good now how it is. π
Thanks again for your great help!
hola
I have a dynamic feed-in tariff on my solar export, which is 16 cents per kWh for the first 15kWh per day, then drops to 5 cents per kWh for the rest of the day. I already have an input_number that I use for my exports in my energy dashboard, but I'm at a bit of a loss as to how I can automate this to change from 16c to 5c. The missing link (I think) is a sensor that's triggered at 15kWh of export, which resets daily.
Have you tried adding a threshold helper? That can then read the "total export" number. Then you can test in a template sensor whether the threshold is ON or OFF and use different values based on that?
do you have the daily export?
state: "{{ 0.16 if states('sensor.daily_export') | float <= 15 else 0.05 }}"
availability: "{{ has_value('sensor.daily_export') }}"
Def. simpler than my suggestion π
Hello, no idea ? thanks
there are no templates involved in that, you will get more answers in #integrations-archived
Not 100% sure if this is the right channel, but I'm attempting to grab local info from my PurpleAir sensor via RESTful sensor. I'm following the link here: https://community.home-assistant.io/t/purpleair-local-api/579387 However, I'm getting this error when attempting to save:
Invalid config for [sensor.rest]: [sensor] is an invalid option for [sensor.rest]. Check: sensor.rest->sensor. (See ?, line ?).
https://paste.debian.net/plain/1295355
^ my setup in sensors.yaml
check the docs https://www.home-assistant.io/integrations/sensor.rest
the link you are referring to is using this:
https://www.home-assistant.io/integrations/rest/
which doesn't belong in sensor.yaml, but under it's own rest: integration\
and this question is also not related to this channel, but to #integrations-archived
Hi!
I know the total measure of energy spent according to the connected meter (Linky, french).
Some appliances have their own SmartPlugs on which I measure the consumption.
So, the difference between total - measured = not measured, the below template.
I could make the whole work yesterday/today, and getting some help from you (thanks!)
Problem is, while setting this NotMeasuredEnergy template in the Energy dashboard, first 2 hours where perfectly fine but now I I can see a (relatively big) negative value.
Which doesn't exist, of course - I'm not producing energy - I wish π
Question is: see the template below, doesn't what I wrote supposed to avoid negative values?
Did I made a boo boo somewhere?
Thanks for your help!
- sensor:
- name: NotMeasuredEnergy
unit_of_measurement: kWh
device_class: energy
state_class: total
state: >-
{% set Tot = states('sensor.MeterTotalEnergy') | float %}
{% set Measured = states('sensor.MeasuredEnergy') | float %}
{% if Tot < Measured %}
none
{% elif (Tot - Measured) < 0 %}
none
{% else %}
{{ Tot - Measured | round(3)}}
{% endif %}
Picture here:
https://snipboard.io/4HiMzE.jpg
(note I resetted all stats couple hours ago in deleting the db, which is why there's nothing before)
Also - I'm not sure if class of this template should be total or total_increasing... read about it, maybe tired, too old, or not my language (probably both), still not sure
Trying to get an average of durations between a few dates, but not sure how to actually calculate the average of the time deltas.
Here is what I have so far and it gives me a list of everything, but I can't use the average() function on data.value.
{% set data = namespace(value=[]) %}
{% set pTime = namespace(value=0) %}
{% for row in state_attr('sensor.xxx','results') %}
{% if count.value != 0 %}
{% set data.value = data.value + [pTime.value - as_datetime(row.get('start'))] %}
{% endif %}
{% set pTime.value = as_datetime(row.get('end')) %}
{% set count.value = count.value + 1 %}
{% endfor %}```
I've set up other templates similar to this where I used as_timestamp() instead of as_datetime() but that then doesn't account for differences in the dates and I need that in there.
I don't know, but "set pTime = namespace(value=)0" seems to me bizarre (0 after the parenthesis)
Oops, just a typo when transferring it over to Discord haha
as_timestamp() absolutely does take into account dates.
Hmm maybe I need to take another look at it then tomorrow because I wasn't getting what I thought. Thanks for clarifying!
That function gives you the number of seconds since Jan 1 1970 UTC
So if you subtract two timestamps you just get the number of seconds between them
That's what I had thought but I wasn't getting the answer I was expecting. Might look at my data too and make sure it looks accurate
Actually, I just now realized what I was doing wrong π€¦πΏββοΈ I copied the code from another sensor I had to get the time between events, and this one I want to average of events so I just need to subtract the end from the beginning of this row
I was looking at Petro's seasons.yaml template and I think I can adapt it for what I am trying to do. (Basically, return a holiday name if the date range matches or return none.)
A couple of questions come to mind:
- How often does a template update?
- Can it be forced to update at a specified interval?
- Is there are way for ensure a state change occurs? Even if the state goes to something else just for a moment (like, initializing) and then holiday/none.
When its entities update or once a minute if it includes now(), and with a trigger
The template does use now() but updating every minute is overkill for what I'm looking for (perhaps every hour or two). But, with that in mind, I'm thinking I can make an automation that runs hourly, sets the state of an input_helper to "initializing", waits a second or two, and then sets the state to the value of the template. That should give me the change that I need.
Sounds complicated when you can just add a trigger
Do you mean a trigger in an automation? I don't need the state change to actually trigger an automation. Instead, it is for something waaay different.
I'm actually looking to be able to use it with lovelace-animated-background. It reacts to state changes (example shows a weather sensor and then showing a background based on its state). But, I'm not trying to work with weather; I want holidays. But, an hourly state change would also change the background to a random default one (every day backgrounds).
Okay. I think I see what you're saying. Basically, create a template sensor with a time_pattern trigger of hours: "/1" and then Petro's modified yaml in the sensor section.
I'm assuming this means that when now() updates, it won't update the entire sensor because the trigger has not fired.
Right
We have two lists:
['Kitchen','TV Livingroom', 'Bed Bedroom', 'TV Bedroom']
['Livingroom', 'Bedroom']
Could we filter the first list to get the items that contain any of the elements of the second list without using for, just with the Jinja filters?
{% set list1 = ['Kitchen','TV Livingroom', 'Bed Bedroom', 'TV Bedroom'] %}
{% set list2 = ['Livingroom', 'Bedroom'] %}
{{ list1 | select('search', list2 | join('|')) | list }}
Do note it is case sensitive
You saved me again! Thanks!
What does the '|' means?
Is it just join them with the | separator or is it a special Charakter?
It's or in regex
time to learn more about regex π
I have made a template sensor and it is kinda working. The sensor gets its update from a attribute I get from Tibber with energy price information. It works fine for a couple of days, even maybee some more. The it get stuck in VERY_EXPNSIVE causing all my heat going into save mode instead of adjust the temp according to the price level. The attribute in the original sensor seems to update fine, and if I restart my RPi with HA on, then it works fine again for some days. Have I done anything wrong in my sensor? ```template:
- sensor:
- unique_id: energy_price_level
name: "PrisnivΓ₯ StrΓΈm"
state: >-
{% set price_level = state_attr('sensor.electricity_price_hjemme', 'price_level') %}
{{ price_level if price_level is defined else 'NORMAL' }}
- unique_id: energy_price_level
Price level will always be defined, you are defining it yourself
If the attribute doesn't exist, price_level will be none, but it will be defined
{{ state_attr('sensor.electricity_price_hjemme', 'price_level') | default ('NORMAL', true) }}
That will do what you intended to do
Makes sense, so like this then: ```template:
- sensor:
- unique_id: energy_price_level
name: "PrisnivΓ₯ StrΓΈm"
state: >-
{{ state_attr('sensor.electricity_price_hjemme', 'price_level') | default('NORMAL') }}````
- unique_id: energy_price_level
You removed , true in the default filter
Without it it won't replace none with your default value
Silly me...
But that said, looks like there actally are issuses with the atribute in the price sensor, as it for now hasnt updated as it should have done. Filed an Issue on it, on Tibber Data page on Github, hope I get som response there. But thanks for your help with the sensor.
@steel swift I converted your message into a file since it's above 15 lines :+1:
@steel swift that would work as well, but remove the unit_of_measurement
With that included only numeric states are accepted.
And either add defaults for your float filters, or add an availability template
I removed unit of measurement before I implemented it. I will probably add a default values. Thank you again for your help π
@mellow sigil I converted your message into a file since it's above 15 lines :+1:
https://snipboard.io/BQYoDj.jpg - sorry for the long message
what you see there is not because the template sensor had negative values
they just were lower than the previous value
you are not looking at the state, you are looking at the delta between the states
because of what I just said.
you are useing a sensor with state_class: total
which means that if the state is eg 20 at one point, and then changes to 15 it will see that as a energy return of 5
ohhh so what should I use to see the difference between total energy (meter) and measured one (smartplugs) ? state_class: measure or something like this?
BTW your whole if statement in the state template is not needed, they can never be below 0 as you already account for that in the availablity
^ I know, but it wasn't working, so I doubled the tests
your problem is that they will update on a different timing
so if the measured one will update first, before the total one does, then your value will decrease
furthermore, your total one probably comes from your meter, which will be accurate, the measured one will never be
accuracy I don't care, yes the total is the meter (Linky), if that makes -0.01 kwh difference I don't care
but you're right on the timing... you mean fixing this would give correct results?
I don't have to change the state_class?
well the inaccurate results will cause issues like this
it's nice to have a sensor to measure the unmeasured energy, but the long term statistics will be crappy, and so will the display on the Energy dashboard
but maybe they have some solutions in #energy-archived
oh - wrong topic, sorry... how would you fix the timing, with a "timer" event every minute where all 3 totals are calculated (almost) at the same time?
OK I'll post in energy channel - million thanks @marble jackal
Stupid question...
When I play in dev tools/Model with a template of sensor setting a State to this sensor, does it NOT actually modify the sensor's real State?
I mean, I hope...
no
ooof thank you!
what you're describing would probably just be a syntax error
I meant I hope it doesn't really update the real sensor State.
I understand, but it's just broken syntax and wouldn't do anything at all
as in, this is nonsense and just results in a syntax error: {{ set states('sensor.aarlo_battery_level_family_room') = 5 }}
ok thanks Rob - please have a good one!
@karmic sapphire I converted your message into a file since it's above 15 lines :+1:
Ive got a weird thing. I have a template sensor i was mucking around with via the UI helpers area, now for some reason its showing a warning, and there is no way to delete it.... any ideas? https://imgur.com/a/z5acSXJ
Or at you referring to changing a state in developer tools > states?
Hey all, any ideas why this Utility Meter sensor is updating every 5minutes - I am trying to get it to record every 30minutes hence the cron
30minconsumption_no_defined:
source: sensor.consumed_today_watts_nodef
cron: "*/30 * * * *"
periodically_resetting: true```
But it is giving results every 5minutes?
https://snipboard.io/qFI6kG.jpg
`last_reset: 2023-10-19T08:00:00.007476+00:00` does show every 30minutes, rather than 5. Have I misunderstood something of how it works?
This is a question for #integrations-archived
Ok sure my bad, thanks
Hello everybody,
Is there a way to remove all non-numeric characters from a string?
something like this {{ 'test123asd'|select('in','.-0123456789')|join }}
Thanks! Exactly what I was looking for!
Is there any way to filter for a spefic device model without a for?
Get from the state.sensor all the entities (or device_ids) that have a device model 'SYMFONISK Sound Controller'.
|rejectattr('entity_id', 'search', '_updated|test')
|selectattr('attributes.device_model', 'defined')
|selectattr('attributes.device_model', 'contains', 'SYMFO')) %}
{{x.entity_id}}
{{x.attributes.device_model}}
{% endfor %}
ah..sorry... WITHOUT a for...no clue, sorry for that
I'm sorry that you had to type all that without helping π
deadly tired indeed π
that won't work anyway, as the device model is an attribute of the device, not of the sensor itself. Or am I misunderstanding that?
But I don't think that's possible without a for loop, als is_device_attr is not available as a test like is_state_attr is
Iβll put a pr for that when I get back from vaca
Enjoy your vacation
Hello! Can we get access to some random input_datetime objects from template? For example {{ input_datetime.light_facade_turn_on_time }} gives an error "UndefinedError: 'input_datetime' is undefined" (both in template editor and in 'variables' section in automation). Feels like it's out of scope...
The state of some random input_datetime? Voila! π
{{ (states.input_datetime | list| random).state }}
Okay, not so random π
I got it worked with help of @inner mesa 's link, {{ states('input_datetime.light_facade_turn_on_time') }} {{ states.input_datetime.light_facade_turn_on_time.state }} but still not fully understand the syntax. In first option states('entity') returns array of all entity states, if it has more than one state? In second option, what does .state in the end mean?
There's only one state
There is a box on that page that explains why the first is preferred
oh, then the function name 'states' instead of 'state' sounds a bit confusing(
Yes, it is
does mushroom template not regard this type of code for changing the icon color?
{% if index > 300 %}
Red
{% elif index > 200 %}
Orange
{% elif index > 150 %}
Yellow
{% elif index > 100 %}
Yellow
{% elif index > 50 %}
Blue
{% elif index >= 0 %}
Green
{% else %}
unknown
{% endif %}```
Color names need to be lowercase
states.sensor
| map(attribute='entity_id')
| select('is_device_attr', 'model', 'whatever')
| list
oh that was easy thanks! I thought I already tried that
That would work if is_device_attr would be a test, which it isn't
Petro already mentioned above he will create a PR for that
You can also remove the else to let it use grey when nothing matches
ive also been trying to get this to work: https://github.com/renemarc/home-assistant-config/blob/775d60ad436cd0f432d2260e503b530920041165/sensors/atmosphere.yaml
I get all kinds of errors, I am trying to understand why it wont read any of my waqi sensors, I put them all in a group.waqi but it still doesnt work
With respect, it is. This exact code works for me:
switches = states.sensor
| map(attribute='entity_id')
| select('is_device_attr', 'model', 'ZEN32')
| list
self.tests["is_device_attr"] = hassfunction(is_device_attr, pass_eval_context) 
Petro is fast π
Keep testing the test
I tested my tests to test the test, and after some tests I can attest it does work as a test
Sorry for the confusion @tawny sedge
I think I had a PR open for that a while ago that I abandoned
Any way to get variable type in template? Something like 'typeof(some_strange_variable)' would be very helpful for debugging!
Not in that general sense, no
You can test directly for some types, but even that is incomplete and a pain the neck
That's why there are some custom tests that were added for HA, like is_number
Then if understand correctly, in the next two examples I get the time as 'string' and 'timestamp' objects. If the 'strings' comparison doesn't seem logical, that's okay. But how can I compare two 'timestamp' objects? I thought there was something like an overloaded operators '<' and '>' for 'timestamp', but all expressions always return 'false' ```{% set turn_on_time_string = state_attr('input_datetime.light_facade_turn_on_time', 'timestamp') | timestamp_custom('%H:%M', false) %}
{% set turn_off_time_string = state_attr('input_datetime.light_facade_turn_on_time', 'timestamp') | timestamp_custom('%H:%M', false) %}
{% set turn_off_time_timestamp = states('input_datetime.light_facade_turn_on_time') %}
{% set turn_on_time_timestamp = states('input_datetime.light_facade_turn_on_time') %}
{{turn_on_time_string < turn_off_time_string}}
{{turn_on_time_string > turn_off_time_string}}
{{turn_off_time_timestamp < turn_on_time_timestamp}}
{{turn_off_time_timestamp > turn_on_time_timestamp}}```
probably i should use some function for comparision?
ah
nevermind
it was wrong input_datetimes. Assigned "input_datetime.turn_on" values for both "turn_on_time" and "turn_off_time" variables π
There is an open PR for additional tests for the other types like list or datetime
I'm really struggling with the round() function. I'd like it to just round to a whole number. Can anyone help?:
Kelvin: {{ test | round(0) }}
Farenheit: {{ test | float(0) * 9 / 5 - 459.67 | round(0)}}```
Output ends up as:
```Kelvin: 289
Farenheit: 60.84800000000007```
I'd just expect Farenheit to result in 61
Farenheit: {{ (test | float(0) * 9 / 5 - 459.67) | round(0)}} = 61
order of operations matters
Hrm. OK. I assumed left to right would be the default I guess?
Filters are applied first (from left to right if there are multiple)
So you were only rounding 459.68
{{ state_attr('') }} is the jinja equiv to [[[ states[''].attributes]]], right?
or is it states.attributes['']
Yes, otherwise something like this would not work
states() | float + states() | float
drawing a blank and I cant google it atm
That makes sense. Thank you!
state_attr() is the preferred approach states[].attributes would also work
thanks Fes -- am in a meeting and jotting things down -- trying to do something like [[[ return (integer variable) || 0; ]]] <-- that will return the variable, unless it cant, then instead return 0, if I remember right, yes?
no, I think thats backwards, isnt it
is that doable with jinja?
i would think its an if else, right?
(I am working on a scene for my livingroom to dim the lights to 1%, turn the back ones off, and then brighten the fronts to ~20% red)
since my lights dont support the transition property, I have to do it via scripts and templates
{{ (state_attr('light.light', 'rgb_color')[0] | float + increment_x)) if (state_attr('light.light', 'rgb_color')[0] | float + increment_x)) >= 0 else 0 }}
keeps giving me message malformed -- is it the parens?
@mellow sigil I converted your message into a file since it's above 15 lines :+1:
On this graph the meter is stating -89 kWH for 1 minute or so π
Sorry, always forgot the 15 lines limit, apologizes.
@marble jackal have you ever had any issues with this kicking out after just a few iterations? The script you sent is only adjusting a couple times, then ending as complete.
Works fine here
what is your input for the script
was a 2-member light group
it only seems to happen when transitioning color
i think I fixed it -- change the abs value to something higher and have been testing
If it should be fixed in the script, can you issue a PR for it so I can check it and correct it for myself π
Or create an issue
I'll be honest with you - I dont know how ... is that push or pull?
i can do the issue π
gotcha brother
Pull, but an issue is fine
π
is it possible to get the volume_level of a mediaplayer? to check it
i tried {{ state_attr('media_player.aarons_room_display', 'volume') }} but it didnt give me anything useful
check developer tools > states for the attributes of the entity and you will notice the attribute is called volume_level
and possibly only available when the device is on
I am testing variables in an automation. I get no errors on this, but is the double quotes neccesary?
action:
- variables:
sun_is_rising: "{{ is_state('sun.sun', 'rising') }}"
- choose:
- conditions:
- "{{ states('sensor.daytime') in ['skumring2', 'skumring', 'dagtid'] }}"
- "{{ sun_is_rising }}"
Yes
Another way of writing it without double quotes would be :
action:
- variables:
sun_is_rising: >
{{ is_state('sun.sun', 'rising') }}
No, it can be integer, float, ...
Thank you for enlightening my knowledge.
BTW Chat GPT wrote this part of the script. Or optimized my old version π Facinating π
Forgot to point out if this also goes for the conditions:
- choose:
- conditions:
- "{{ states('sensor.daytime') in ['skumring2', 'skumring', 'dagtid'] }}"
- "{{ sun_is_rising }}"
meaning; the double quotes must be there?
yes
What's the efficient way to check in a template if we are between some two days in the year spanning New Year, e.g. 1 September and 1 March
@earnest cosmos See the first rule.
It needs to be a yaml string so the engine can understand by the parentheses that it needs to render it as a jinja template
https://www.home-assistant.io/docs/configuration/templating/#important-template-rules
Can I use a macro in a while loop? Will it re-evaluate the macro with each loop?
You can use a macro like any other function within a for loop
check if now is not in the period not spanning the new year is easiest
{{ not as_local(as_datetime(now().year ~ '-03-01')) < now() < as_local(as_datetime(now().year ~ '-09-01')) }}
great!
I don't know if this is the correct place to ask this. I have two sensors, both numeric. Is there a way to create a new one that is the product of both? In the helpers there is only SUM, not PRODUCT.
sensor1 * sensor 2. like 4*2 = 8
uhm, use a helper?
You'd need to make a template sensor
that's what I meant, with my noobish reply
You can make a sensor group of type Product
Helpers it is π
I didn't saw the Product available, before
It seems to overlap the 'combine multiple sensors' helper, which lacks that
I don't know why there are two dissimilar ways to 'combine' sensors with that much overlap
I have another question. On top of the product, I also need to divide by 100, for this I must create a static entity with value=100 right?
that was the one I saw before, where product isn't available
yes, I think that one was create first, and then the group one was created. I would say the combine one should be removed, but my guess is that it's tricky to do that in a non breaking way (copying them over to the group one automagically)
but hey, I'm still halfway my Python intermediate course and cancelled the Codecademy subscription before I had to start paying π
I think that 'group' is a much less descriptive way to put it. It's hidden away where nobody will find it
what about this? "Number" helper doesn't work for this
I'd suggest just using a template sensor to keep things together if you're going to need additional logic.
Yes, you can create a template helper so you don't have to do the YAML
but it depends a bit on what you want to do if the source sensors are unavailable
I have a templte value like this {% set duration = as_timestamp(now()) - as_timestamp(states.sensor.tv_letto_yearly_on_temp.last_changed) %} how can I show something like HH:mm:ss ? it is not 24h only, but in duration there is how much time my tv was on in the full year
{{ duration | timestamp_custom('%H:%M', false) }}
I have a template that uses now() causing it to update every minute. Is there a way to control how often it actually updates?
So I'd create a trigger sensor that updates every X mins and spits out the timestamp and then use that value instead of now(). Is that the idea?
no
add a trigger to the template sensor
whole section in the docs on this: https://www.home-assistant.io/integrations/template/#rate-limiting-updates
Ah ok, I was on the trigger docs. Let me take a look, thanks
Ok so to make sure I understand, the trigger will be the only thing controlling when the template updates and nothing in the template
I think I was confused because I was still thinking things in the template would cause a trigger
So for instance if one of the sensors in the template updated, it wouldn't update the sensor, it's ONLY updating at the interval
I think the method I described would still keep the template updating when the other sensors in the template update. But depending on the use case that might not matter
add whatever you want to the trigger
For more context, I'm making a sensor that says the estimated timestamp when a battery will be drained. So I have a template that was using the battery level state and a derivative sensor
Yeah that's also true
Could just manually add the sensors I'm using to the trigger
Just when I think I can use a sensor in the UI, the yaml pulls me back in lol
I wonder if it would be cleaner to do it my way though... Make a sensor that updates every X mins and spits out the timestamp. Then I can take my existing template and just replace now() with states('sensor.5_min_timestamp') or whatever
That would be reusable as well. Though kinda awkward to have a sensor for that.
Yeah sorry, nothing against YAML, just considering alternatives
I think if I cared about it updating when the battery sensors updated my solution would be more attractive than it is
Because it does feel awkward to have to specify them manually as triggers
And if this is something I'd want to do a lot, I think the reusability of the sensor is desirable
Can anyone please help me with my automation https://pastebin.com/K8FwhfPe , I think the problem lies with the value_template: "{{ 'days' in trigger.calendar_event.summary }}" I just can't figure out how to write it??
Quick explanation about what you want this automation to do and what actual behavior you're seeing would help. Your automation title of "chicken" doesn't really help π
what is wrong with the yearly template sensor counter? it always shows 00:00:00 while tv is on, and start to count when it is off
https://pastebin.com/v3Z1HEdd
Ok so I want to use 2 of my motion sensors as triggers and then a combination of helper switches and calendar entries to run an automation. the condition is that Each day of the week has it's own helper switch, and each calendar day, between 8 and 11PM has the day of the week in the summary
the problem I'm having is with the calendar condition, I want it to fire with the calendar "on" and the summary
Have you tried using the trace feature for your automations?
Also have you tried using the template dev tools to validate your templates?
The trace tool will help show you what values are such as in the triggers and then you can use that to fill in values when using the template dev tools
I never used any of those, but so far never had an automation this complex, will give it a try
it's the value_template that's not correct:
- condition: state
entity_id: calendar.menu
state: "on"
- condition: template
value_template: "{{ 'sunday' in trigger.calendar_event.summary }}"
How would you put a condition that the calendar is on with a specific summary word? I used https://community.home-assistant.io/t/calendar-based-triggers/501795 as a guide line\
Ok I figured it out, answer was here: https://community.home-assistant.io/t/automation-calendar-conditions/558496 thx for the help!
Use a utility meter for that, your template sensor will not work like this.
If you really really want to use a template sensor you need to use a trigger based template sensor to be able to restore the state after a restart
yeah, I get that, but if I use directly the history_stats it should work as expected? I mean it will restore after restart and it will be reseted only at the end of the year?
I mean this:
- platform: history_stats name: "TV letto yearly on" entity_id: switch.tv_letto_switch state: "on" type: time start: "{{ now().replace(month=1, day=1, hour=0, minute=0, second=0) }}" end: "{{ now() }}"
That will only work if you have all that data in your databases
ah ok, so I need to create an helper for that, got it, thanks
and there is a way to change the format for the meter unit?
How can I create a helper with attributes?
Example: I would like a light helper with binary state (on/off) and integer/float attributes for previous_color and previous_brightness.
These values would be set and read by several automations.
Hi there,
We have a few window blinds that can be controlled (tilt and lift), however, the lift function should only allow a rango of 0% till 80% (when using more than 80% the ropes will jam as 80% is 100% in the physical space). Currenlty i have a few buttons that have preset values in them.
Now i want to add the entity to homekit, however, it gives the full control (over 80% lift). Is there a way to 'simulate' the entity where the lift will have a translated value, so that 100% is actually 80%?
Thanks, i'll take a look at that π
I'm using one for my venetian blinds. I just want them to operate between 0 and 50% (50% is open and everything else would be closing the other direction)
I can share my code as an inspiration (you would have to modify everything to your needs)
Awesome, that will help me out a lot β€οΈ
You can't use that 1:1 for usual blinds. But with the documentation, you should be able to modify it
Is there official documentation for home assistant? I've been searching the internet for days and I haven't found any relevant information.
Thanks. I don't know why the search engine never found that.
how can I keep the data for an history_stat sensor for one year? utility meter is ok, but the original format is hh:mm:ss and it just keeps a number
https://pastebin.com/k0v3kMXM I ahev an issue with templating actions part. It says that extra keys are not allowed in section actions.
Do you have some hints on this?
The actions section needs to be within another data section within data. So data -> data-> actions
https://companion.home-assistant.io/docs/notifications/actionable-notifications/#building-actionable-notifications
Youβll need to clarify if you want to save all the data or just the statistics data. Hereβs a nice description I found on the forums:
If long-term statistics are sufficient then the post a few down from that has the requirements:
I have a z-wave magnetic binary_sensor on my garage door that has zome bounce when open/closing messing up my automations. Some searching looks like I want to use delay_on and delay_off to add some debounce to solve this, seems reasonable, but I'm not sure the intended way to do this. It seems I can't add these parameters to the door sensor itself, rather I create a template that wraps the existing sensor and creates a new one? Is this true? If anyone has an example I would be grateful as all of my attempts so far have failed.
This is what I have now:
`template:
- binary_sensor:
- name: Garage Door Debounced
state: "{{is_state('binary_sensor.garage_door_window_door_is_open', 'opened')}}"
delay_on:
seconds: 1
delay_off:
seconds: 1`
- name: Garage Door Debounced
a binary_sensor will never have a state of opened
it can be on, off, unavailable, or unknown
otherwise, there's nothing wrong with creating a template sensor to debounce, as you've done
I see, thanks
@mighty ledge Can you help me understand something regarding your seasons.yaml ? In the events, you define yaml ('halloween', md(10,8) | as_datetime ), ('soft', md(10,31) | as_datetime ),where soft corresponds with scene.holiday_bulbs_soft_white.
Does this mean between October 8 - 30 the Halloween scene will be active but on October 31 the soft scene will be active? Shouldn't it have a + timedelta(days=1) to ensure your spooky scene is active on Halloween?
I'm guessing you're looking at an old version?
was updated two weeks ago
not sure why it's showing 10,31 for you?
showing 11,1 for me π€£
All I changed in my last update was to have the lights for the full month of october
Gotcha. I just looked and do see that change made. You must have done it right after I started looking into it. Which is weird because I was asking about it a week ago. #templates-archived message
Maybe I had already copied the code into Dev Tools beforehand.
π€·ββοΈ
On these 'seaonal' things, I have calendars as well covering those....could you maybe elaborate on the benefits that YOU see with the yaml one? I like HA for its flexibility but am sometimes getting 'nuts' on what to choose and thus need use cases π
I intend on using the yaml one to determine if there is a holiday season scheduled (per the events); if not, then it returns none, for example. (The equivalent to Petro's soft scene.) The entity will then be able to be used to change the animated-background on my tablet dashboards. A time_pattern trigger will be added so the sensor can be updated hourly, thus triggering a state change the animated-background can see.
I decided to go this route as it let's me define what holidays I want to incorporate into the backgrounds and does not include holidays that I don't. Additionally, one of the scheduling calendars I looked at would only do Federal holidays but not "lesser" holidays.
I am counting how much time the TV is on, and grouping this count per day/month/year, since my recorder is configured to keep data for max 30 days, the problem is only with the year data, so what is the best way to do it?
Ever looked at this... ? https://www.home-assistant.io/integrations/history_stats/
I do admit that I am not sure about VERY long term ... I use them to ttrack my sons gaming PC on and my daughters lights
my sensors are history_stats, but it keeps the data for time that I cofigured the recorder, not longer
Check... I did not know this until now...which makes the wording 'stats' a bit misleading vs the other stats...or maybe not...history is related to the rec-history...anyhow...not 100% transparent to mix the both (for me) π
yeah, history_stats is not statistics
It keeps every data point for the time configured in the recorder. If you have the sensor configured in a way that allows statistics to be captured, it will keep the statistics data forever (in a data table not controlled by the recorder settings). If all you want is hourly/monthly/yearly, then statistics should be sufficient
this is how they are configured https://pastebin.com/v9S6uYh3 , so statistcs are already there, if I am correct, right?
From the second link in my first reply:
For long term statistics to be generated for a sensor⦠all it needs is a valid
device_classastate_classofmeasurementand aunit_of_measurement
Do you see each of those things specified in your sensor config?
<template TemplateState(<state sensor.tv_letto_yearly_on=10.95; state_class=measurement, unit_of_measurement=h, device_class=duration, icon=mdi:chart-line, friendly_name=TV letto yearly on @ 2023-10-21T14:51:17.658095+02:00>)> it iseems so, right?
Looks good to me π
ok, so I have thsi data forever in statistics
To verify it is there, add a statistics card to a dashboard to plot it out
yes, I did and I can see the data in the graph-statisitcs card
To be clear, you have the statistics data forever. You donβt have every data point
yes, but I just need the hours count per year, I already have other sensor for aggregation per day/week/month
You donβt get to choose what you want, you either get the statistics data or you donβt. You can read about long term statistics here:
https://www.home-assistant.io/blog/2021/08/04/release-20218/#long-term-statistics
how to store a bunch of playlists of a youtube, and to play it randomly?
for example:
actions not allowed for some reason
Calling homeassistant.update_entity on a trigger-based template sensor should work, right? It's giving me a "not implemented" error: https://github.com/home-assistant/core/issues/102488
does anyone see anything wrong with that simple example?
No, it doesn't
because you may need to grab data from the trigger?
And if it would, it would have the same issue as pressing RUN in the Automation GUI, there is no trigger, do everything relying on the trigger doesn't work
Yeah, I suppose so. Just seems like an unfortunately long and confusing error
The intended use case was to have a sensor updated periodically, but be able to force it sometimes. I guess you'd need an event or some other trigger for that, assuming that you weren't relying on the trigger data
But I know Marius asked about it a while ago, that's how I knew it didn't work π
I think I'd prefer to see it actually try and then fail to resolve some trigger data
the failure shouldn't be due to the service call
If you really want you can of course add a call_service event π
that's what happens with automations and "run", after all
this behaves differently, and kills a useful use case
Yeah, I only know that it doesn't work, never tried it myself. But indeed, it would make sense to allow it, and just log errors about the missing trigger variables
And make the state unknown
there's no sensor.trigger π
in any case, I added some verbiage to the issue and left it open
thanks for pointing that out
is there an easy way to get an entity id from a friendly name in a input dropdown list
Sort of... friendly names aren't required to be unique though, so there is the potential for there to be multiple matches. The most naive way is to do this, but if you can filter it to a domain, that'd be better
{{ states | selectattr('attributes.friendly_name', 'eq', 'A Name') | map(attribute='entity_id') | first }}
I was trying to do something like this entity_id: "{{ states('input_select.speakers') }}"
for a target
Sure, and that will only work if that's an entity id
So, if you wanted to use the above, it'd be something like
{{ states | selectattr('attributes.friendly_name', 'eq', states('input_select.speakers')) | map(attribute='entity_id') | first }}
equal
ah
thanks
You're welcome
quick question: how can i get calendar events only for the "current day". so in this case... everything from sunday, not monday. however at midnight, i want all from monday, not other days...
i call the service calendar.list_events... i was thinking of calling it once at midnight with a duration of 24h ... but that would mean during the day , the calendar can't update
i'm creating a template sensor for this now, that runs every hour
but then the duration doesn't work...
so i would need a "now" from 00:00:00 until "now" 23:59:59
wait... is it as simple as:
- service: calendar.list_events
data:
start_date_time: "{{ now().date() }}"
duration:
hours: 24
does it "default" the time to 00:00?
{{ today_at() }} will be midnight
I have 2 questions: they both are on things that work, however, i think it could be "better" or at least "prettier" π how would i go about this?
do i start a thread for both? so i don't spam this one? or just ask here?
i get the feeling i'm missing ... concepts of it all. the whole templates,triggers, actions, sensors, variables, attributes are messed up in my head
now().date() just returns today's date. As there is no time info anymore, it will use midnight I guess
But to me it seems a bit of a hack
There are some links in the topic description to guide you
And also in the pinned posts
i've done more hacky things in my life π but i want to do this "well" so i'm looking for guidance
there are many things on the website/forums... but no "best practices"
but i'll have a look
As always there are many ways to skin a cat. I will do things differently than others. But if you have specific questions I can tell how I'd tackle it
i have to leave now, however... this evening, i will be back and if i find the courage, i'll ask π
thanks ina dvance.
is_device_attr is in the code as a test
Yep, it works, so it's usable. No PR needed.
Yeah, I was stupid
Vacation over?
ya
Hello Im getting an error for this variables:
{% set hallway_livingroom_main_light_last_changed = as_timestamp(states.light.hallway_livingroom_main_light.last_changed) %}
{% set rotary_encoder_last_changed = as_timestamp(states.binary_sensor.hallway_actuator_button.last_changed) %}
error:
ValueError: Template error: as_timestamp got invalid input '' when rendering template '{% set hallway_livingroom_main_light_last_changed = as_timestamp(states.light.hallway_livingroom_main_light.last_changed) %} {% set rotary_encoder_last_changed = as_timestamp(states.binary_sensor.hallway_actuator_button.last_changed) %}' but no default was specified
What does it mean bu default value?
'None' has no attribute 'last_changed' => when I just put {{states.binary_sensor.hallway_actuator_button.last_changed}}
I need for this sensor on this image https://i.imgur.com/6oE6yMp.png last_changed when it was in state 'on'
hm but how can I do that via templates
@sonic nimbus You probably have a typo in the entity_id
That error indicates the entity_id doesn't exist
encoder vs actuator
how to translate a float(number_of_hours) in a readable time format?
(float(number_of_hours) * 3600) | timestamp_custom('%H:%M'), false)
even if the hours are more than 24?
You still can... you just need to add the correct properties in, actions needs to be nested in another data section
No, in that case not
that is my problem, the number of hours that I have in the sensor is greater than 24
Check https://strftime.org
it counts the number of hours that a device is on in a year, so I can't predict
You can use %-j but then you need to subtract 1 from it
But how relevant is the number of hours if you are already counting days?
Do you really care if it's 12 days and 3 hours, or is 12 days enough?
Anyway, you can have a look at https://github.com/TheFes/relative-time-plus or https://github.com/Petro31/easy-time-jinja
for me is even good if I can have something like 12323:34:34 where the first number are the hours
I just need the hh:mm:ss doesn't matter if the hours are more than 24
So what does your sensor give? You just want to convert 5.5 to 5:30?
Hello. I am new to Home assitant. I would like to be able to turn the screen of my lg oled black. I found something on the web but i dont know how to implement this code in home assitant. Looking forward for you help (:
https://community.home-assistant.io/t/is-there-a-way-to-turn-lg-webos-tv-screen-off/197585/17
Have you added the WebOS Smart TV integration to your Home Assistant instance?
yes
i just dont know where to put the code
if you want i can screenshare for you and you can explain it to me in vc
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
like this is the code i want to implement. but where in the web interface do i put it?
@haughty breach
That is a Template Switch, though it is missing the switch: key at the top. The easiest place to put it is in your configuration.yaml file. If you don't know how to access it, you can find details at https://www.home-assistant.io/docs/configuration/#editing-configurationyaml
I have a dumb templates question: I have 2 temp sensors that I want to reformat the output of. Do I have to do a replace template for each one?
That is, is there any way to say if device type = X, reformat output as Y
I successfully added the configuration and it is compiling. Now how can i send the command to turn off the screen?
I have a working template to reformat the reported value for a sensor that is reporting a temperature, but I have 2 devices that need this reformatting. I don't see any way to duplicate the template, but it seems the only way to get the identical formatting applied to 2 different sensors is to create 2 templates with each one specifying the entity's value that is to be reformatted. Is there a way to create a template so it applies to multiple specified entities?
Never mind, the answer is yes there is a way
@fast lotus I converted your message into a file since it's above 15 lines :+1:
Hello Guys,
Newbie here, so I'm working with Mushroom to create a mobile Dashboard and I really like it but I have a question now. I want to create a Button where I click and I call a service and open my Lock of the House. So my Idea is the Icon Color is red (as the Lock is closed) when I now make my primary Action which is calling my Service to Open my Lock I want to change the Icon Color to Green then wait 5 Seconds and make it switch back to red. I hope you know what I mean. My Code at the moment is this: https://dpaste.org/8Bo4Z
Is something like this even possible to make with mushroom and what would be the way to go? Much thanks in advance for your help!
Do you know there's a Mushroom lock card? https://github.com/piitaya/lovelace-mushroom/blob/main/docs/cards/lock.md
Yeah but that doesn't work for me because its no lock what I can lock and unlock its just a service with open the door downstairs and for my flat I don't have a smartlock didn't get It working how I like it
Want it to look like this: https://imgur.com/a/T1f4ci5
Hi Y'all, not sure if this is the right place to ask this question so please let me know if I'm in the wrong place.
I am trying to create a custom intent and intent script that has some basic logic to define the response. The log is as follows and works in the Template tester:
{% if float(states('sensor.soil_moisture_2')) > 30 %}
{{'Fittonia is not thirsty!'}}
{% elif float(states('sensor.soil_moisture_2')) < 30 %}
{{'Fittonia is thirsty!'}}
{% endif %}
Those tests are the same
Yeah sorry, edited to fix it
You just need an 'else'
I am trying to get this into my config.yaml in the intent script but I can't seem to figure out how to properly use the if statement with the intent_script. This is what I tried that didnt work:
intent_script:
FittoniaThirsty:
speech: >
{% if float(states('sensor.soil_moisture_2')) > 30 %}
text: "Fittonia is not thirsty!
{% elif float(states('sensor.soil_moisture_2')) < 30 %}
text: "Fittonia is thirsty!"
{% endif %}
You can't template keys like that
Bummer
you don't need to
I have no experience with intents, but it's a simple change
intent_script:
FittoniaThirsty:
speech:
text: "{{ iif(states('sensor.soil_moisture_2')|float > 30, 'Fittonia is not thirsty!', 'Fittonia is thirsty!') }}"
I don't even know if you can put a template there...
Looks like its working!
ok, looks like you can
Oh bummer, can't post the screenshot of the assistant's resposne...so I guess trust me it worked?
no need, I'm sure it worked
lol, thanks!!!!
Any template wizards about that might be able to assist me with something that's probably very simple?
{{ 'home' if is_state_attr('calendar.xander', 'message', 'Xander\'s Home') and is_state('person.sy', 'home') else 'not_home' }}
That's what I have now, and was working fine until a few weeks ago.
For some reason it fails to action now.
The main issue I have is it seems to change the state to home, at the beginning of the day, I'd prefer for the state to change to home at event start, upon reloading of HA if the event is still live and change to not_home at event end.
I've even tried the calendar events in automations to no avail.
I'm running out of hair to pull out...
Thanks for any assistance in advance
Hi, how can I add two time helpers together and store them in another time helper, as an action in an automation please?
I tried doing something like this:
`action:
- service: input_datetime.set_datetime
data:
time: {{ (as_timestamp(state('helper.medicine_1_reminder_time')) + as_timestamp(state('helper.medicine_1_frequency'))) | timestamp_to_datetime }}
target:
entity_id: input_datetime.medicine_1_reminder_time`
If i set the time to a fixed time example: "12:00:00", it works
so i'm assuming im doing something wrong in the logic to add the helpers together
Where did that template come from? I'd suggest you start by reviewing: https://www.home-assistant.io/docs/configuration/templating/#time
where'd you copy that syntax from?
where are you using that? Template looks fine.
I create an automation from the FE, and set the action to be a service Input Datetime: Set. And set it as static 12:00 first. It worked fine. Then i tried find a way to add the two helpers together
Yes, I get that, but where are you getting that template from?
from bard π
Stop using bard π
it's 100% wrong
find out your entity_id's, that's step 1
once you have those, we can help you with a template
but right now, your entity_id's are wrong for both of the helpers.
it even made up filters that don't exist
Stop using AI in general and learn this stuff yourself. AI for HA is typically wrong
I have these helpers: input_datetime.medicine_1_next_reminder_time and input_datetime.medicine_1_frequency. What I want is to updateinput_datetime.medicine_1_next_reminder_time with the value of input_datetime.medicine_1_next_reminder_time and input_datetime.medicine_1_frequency together as an action
Got an oil monitor sensor using the rtl_433 add-on reporting to mosquitto that is tracking the height between the top of the tank and the oil, which I'm then converting into the remaining oil via a simple template:
{% set currentDistanceToOil = states('sensor.' ~ states('input_text.oil_tank_sensor_name')) | float %}
{% set fuelDepthRemaining = states('input_number.oil_tank_height') | float + states('input_number.oil_sensor_offset_to_fill_level') | float - currentDistanceToOil | float %}
{% set oilRemaining = (states('input_number.oil_tank_capacity') | float / states('input_number.oil_tank_height') | float) * fuelDepthRemaining | float %}
{{ '{:.2f}'.format(oilRemaining) }}
However I'm not sure how to handle the initial sensor states('sensor.' ~ states('input_text.oil_tank_sensor_name')) returning unavailable after a HA restart. I thought since mqtt was defaulting to persistance that setting the rtl433 to enable retain would be enough, but it appears that after a full HA restart (causes mosquitto and rtl433 addons to restart) reading the sensor doesn't work until it has transmitted. Looking around the only suggestion I've seeing is to add an automation to trigger on change to the original sensor to set an input number. Is that still the best way to handle persistence?
what are the states of input_datetime.medicine_1_next_reminder_time' and 'input_datetime.medicine_1_frequency', look in developer tools -> states for the raw states.
i'm storing time in them. The state are:
input_datetime.medicine_1_frequency: 00:06:00
input_datetime.medicine_1_next_reminder_time: 16:30:00
ok
gimme a sec
{{ states('input_datetime.medicine_1_next_reminder_time') | today_at + states('input_datetime.medicine_1_frequency') | as_timedelta }}
and
you need to change how you put that template into the service call...
- service: input_datetime.set_datetime
data:
datetime: "{{ states('input_datetime.medicine_1_next_reminder_time') | today_at + states('input_datetime.medicine_1_frequency') | as_timedelta }}"
target:
entity_id: input_datetime.medicine_1_reminder_time
add a default in float for the first line
in general, you can make that template better too
do you have an availability template that goes with that?
if yes, please post the entire sensor configuration.
Also, just looking at your template, it doesn't make sense IMO. The math that is.
it seems you're just using all input helpers for it too. Is this template 100% manual? How are these input entities being populated?
I'd wager there's a much better way to handle this, I can help you with the template.
@weary frigate ^
@mighty ledge are you suggesting the default for the float should be the current value? I had that and it resulted in various things thinking the tank was full for a period and messing up counters. The template is added via the UI, not seeing any way to add an availability template. However if I do use one, would that not result in any cards generated based on this being also unavailable or invalid until a suitable value is provided by the sensor?
I'm using input helpers as my initial numbers were estimates and I wanted to make it easier to update them. Essentially there is an distance between the oil monitor and the max fill point that needs to be accounted for, then after that a simple max oil vol * (depth of oil remaining / maximum depth of oil when full) to get the proportion of the max oil
Oil sensor is about 8cm higher than the max fill level, so any measurement it gives needs to be adjusted before calculating the proportion of the tank remaining
can you post the full template sensor?
It's made in the GUI (he mentioned that above) so it's not much more than the template
The template is added via the UI
ah I missed that
Well your only option is to add a default for the float value.
otherwise, if you do this in yaml, you can make the sensor go unavailable when the text doesn't resolve to a real value
is the previous value of the template sensor available to use as a default after a restart? I just presumed not
The input_text should be populated at startup with your last value, so the template sensor should never be unavailable. Unless you're doing something with an automation.
not sure why you're using an input_text anyways
as that's the root of your problems
you can use a input_select, that restores state as well
The input text is resolving fine, it's the sensor it references that is unavailable and I can see that when I look directly at it
probably the only one which can be unavailable is 'sensor.' ~ states('input_text.oil_tank_sensor_name')
right, and the only way that happens is if the input_text doesn't have the correct value
as thefes is pointing out
or after restart before the sensor is ready
all input_helpers should restore state instantly, so it should work at startup
ah, I just noticed it's sensor.
so, the problem is with that sensor. and the only way to overcome it is w/ an availability template. Which can only be done in yaml.
The resulting sensor that resolves to is marked unavailable which is the problem. Until it reports in after a restart, I can't seem to paste an screenshot to show it. 'sensor.' ~ states('input_text.oil_tank_sensor_name') resolves to 'sensor.Oil-SonicSmart-145565457'
well, that's an incorrect entity_id
regardless the states will sluggify it
however, the statements still stand
sorry, copy and pasted the wrong text, it's 'sensor.oil_sonicsmart_145565457_d'
the only way to account for it is with an availability template
Which is not possible to define through the UI?
no, as i've said 3 times now
Sorry, didn't spot the message
Hi! I want to have a trigger which will fire at a particular time offset form the next_midnight property of sun.sun, something like
now() > as_local(as_datetime(state_attr('sun.sun','next_midnight'))) - timedelta(hours=10)
I would like to make sure that it doesn't fire if I've missed the time because e,g. HA was offline. Is that guaranteed already here or do I need to have a slightly offset time on the other side of the now(), so that it doesn't resolve to true for more than e.g. a minute around my desired trigger?
you can do:
{% set mn = as_local(as_datetime(state_attr('sun.sun','next_midnight'))) %}
{{ mn - timedelta(minutes=1) > now() > mn }}
yeah -- I was wondering if that's necessary. I guess it is. π Thanks!
Thanks for this. I set it up, works wonders. Where can I find this information going forward so I won't have to ask? π
it's covered in the template documents
you can find all the resources in this channels pins
thank you sir, appreciated π
How would I get this to also account for days?
This is currently false because it's not looking at the date just the time.
{{ ((now() - '2023-10-22 08:20:56.702736-04:00' | as_datetime).seconds > 15 * 60) }}
You can use the total_seconds() method as opposed to the seconds property to get the full duration
you should pretty much only use total_seconds() if you want the full duration in seconds.
I personally never use any of the other attributes unless you're specifically going for the non-day ammount.
How would I use it because I just got
TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int
You're missing ()
Awesome got it
Is there a fixed order in the evaluation of the template sensor's state vs atributes? e.g. For a trigger-based sensor, can I assume that the state will have evaluated prior to the evalution of attributes, so that if i use its value, it is the current one? At least in this.state
in a trigger based template sensor this will be created on the trigger, and will not change
so it's the same for the state and the attributes
for non trigger based template sensors it will update the state first, and after that this.state will be the new state in the attributes
so what happens if I have an attribute that uses this.state in its calculation?
trigger-based
then it will be the previous state (so at the time at the trigger, before the new state is rendered)
ok thanks!
Is there a way to pull out the next event time (or time until next event) for a specifically named recurring event on a Local Calendar?
For example, if I have a calendar with "Event A" recurring twice a week and "Event B" twice a month, is there a template I can use to create template sensors to tell me when the next "Event A" and when the next "Event B" is? Or do I need to use separate Calendars for that?
Easiest would be to use separate calendars, but I think you can get it from calendar.list_event service. There's some newish way to call this from a template, but I'm not clear on the exact details.
hi all, is there an easy way (probably not lol) to convert string 'five' to 5 or any other word number into its int?
I made a forum post about it
in the release it occured in
i'll have to find it
yes but that's not what I asked for. That's the actual opposite
Same idea
I need text to numeric, not numeric to text
Only five or any number?
any